You need to enable JavaScript to run this app. TypeScript中如何为解构参数{html}指定类型解决VS Code报any问题
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何为解构参数{html}指定类型解决VS Code报any问题

TypeScript 解构函数参数的类型标注方案

你不能直接在解构的变量后加类型标注的原因是:解构语法中{键名: 变量名}是属性重命名的语法,你写{html: string}会被TS识别为把参数对象的html属性赋值给名为string的变量,而不是给html标注string类型。

正确的标注方式是给整个参数对象定义类型,有两种常用写法:

写法1:直接内联标注参数对象类型

// 给解构的外层括号加对象类型标注
const concatSource = ({ html }: { html: string }) => {
  // 注意原代码的两个小问题:source未声明、return时拼写错误为souce,这里做了修正
  const source = `
    <html>
        ${html}
    </html>
  `
  return source
}

写法2:提前定义类型别名/接口(适合参数结构复杂或需要复用的场景)

// 提前定义参数的类型
type ConcatSourceOptions = {
  html: string
  // 后续新增参数可以直接在这里扩展
}

const concatSource = ({ html }: ConcatSourceOptions) => {
  const source = `
    <html>
        ${html}
    </html>
  `
  return source
}

两种写法都能正确给html标注string类型,不会再出现any提示。

内容的提问来源于stack exchange,提问作者user310291

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 23:48:03