首页 前端知识 TS2322错误解决方案

TS2322错误解决方案

2024-05-30 10:05:17 前端知识 前端哥 674 306 我要收藏

废话

之前写C#,所以使用强类型的语言比较习惯,用js觉得有些自由散漫了,所以学习学习ts,结果感觉ts也有好多坑,好多限制,但是又不想使用@ts-ingore。多少有点强迫症吧

从网上找了好久都没找到方法。以下方法不一定是主流或正确的做法,只是在webstorm中不会再提示错误了,可以正常编译成js代码和运行。

仅供参考

提示错误的代码

定义一个接口,用来表示自己的类型

export interface Options {
    key1: number;
    key2: boolean;
    key3?: string
}

定义两个Options类型的变量

let options1:Options = {
    key1: 0,
    key2: false
    key3: "option1"
}

let options2:Options = <Options>{
    key1: 3,
    key2: type
}

使用for…in对options1遍历给options2赋值

  • TS2322: Type ‘number | boolean’ is not assignable to type ‘never’.   Type ‘number’ is not assignable to type ‘never’.
let key: keyof Options;
for (key in options) {
    if(option1.hasOwnProperty(key)){
        option2[key]/*ts2322*/ = options[key];
    }
}

  • TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Options’.   No index signature with a parameter of type ‘string’ was found on type ‘Options’.
for (const key in options) {
    if(option1.hasOwnProperty(key)){
        Settings.options[key]/*ts7053*/ = options[key]/*ts7053*/;
    }
}

修改后的代码

将定义的接口继承Record即可,指定key及值的类型

export interface Options extends Record<string, any>
    key1: number;
    key2: boolean
}

说明及参考

TypeScript版本:4.7.4

编辑器webstorm2022.3

【1】TS 里几个常用的内置工具类型(Record、Partial 、 Required 、 Readonly、 Pick 、 Exclude 、 Extract 、 Omit)的使用_ts partial_织_网的博客-CSDN博客

【2】如何在Typescript中使用for…in ? - 掘金 (juejin.cn)

转载请注明出处或者链接地址:https://www.qianduange.cn//article/10044.html
标签
评论
发布的文章

使用 mapstructure 解析 json

2024-06-05 13:06:03

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!