如何让TypeScript理解非可赋值类型的预期逻辑,避免报错?
解决TypeScript中includes方法的类型不兼容问题
针对你遇到的场景,有几种无需使用//@ts-ignore的解决方案:
方法一:类型断言为宽泛类型
直接将变量a断言为string(或unknown),因为includes方法在运行时本身可以接受任意类型的值做判断,只是TypeScript的默认类型定义限制了参数必须是数组元素类型:
type A = 'a' | 'b' | 'c' let a: A const list = ['a', 'b'] as const list.includes(a as string) // 无类型错误
方法二:扩展Array的类型定义
全局扩展ReadonlyArray(或Array)的includes方法类型,让它接受unknown类型的参数,匹配方法的实际运行行为:
// 全局类型扩展,可放在项目的类型定义文件中(如global.d.ts) interface ReadonlyArray<T> { includes(searchElement: unknown, fromIndex?: number): boolean; } // 原代码即可正常使用 type A = 'a' | 'b' | 'c' let a: A const list = ['a', 'b'] as const list.includes(a) // 无类型错误
方法三:使用类型守卫缩小范围
如果需要在判断后对a做进一步的类型安全操作,可以先通过类型守卫缩小a的类型范围,同时也能解决includes的类型报错:
type A = 'a' | 'b' | 'c' let a: A const list = ['a', 'b'] as const type ListItem = typeof list[number] // 自定义类型守卫 function isListItem(value: unknown): value is ListItem { return (list as readonly unknown[]).includes(value) } if (isListItem(a)) { // 此处a的类型被缩小为'a'|'b' console.log(a) } else { // 此处a的类型为'c' console.log('a is not in list') }
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

