TypeScript中使用Pick指定函数返回类型时遇类型错误问题
TypeScript返回类型错误:Pick使用误区解析
问题代码
你定义的两个接口:
interface Foo { a: string, b: boolean | null, c: number }
interface Bar { id: number value: boolean, }
你尝试编写返回Foo中b类型的函数,但代码报错:
const aFunction = (barissimo: Bar | null):Pick<Foo, 'b'> { if(barissimo) return barissimo.value; return null; }
报错信息:
return barissimo.value处:“Type 'boolean' has no properties in common with type 'Pick<Foo, "b">'”return null处:“Type 'null' is not assignable to type 'Pick<Foo, "b">'”
错误原因
你误解了Pick的作用:Pick<Foo, 'b'>会生成一个对象类型,结构是{ b: boolean | null },而你函数返回的是单个值boolean或null,类型完全不匹配,所以触发报错。
正确解法
要获取Foo中属性b的类型,应该用索引访问类型Foo['b'],它直接返回b的类型boolean | null,和你函数返回的值类型完全匹配。修正后的代码:
const aFunction = (barissimo: Bar | null): Foo['b'] => { if(barissimo) return barissimo.value; return null; }
内容的提问来源于stack exchange,提问作者four-eyes
相关产品推荐
相关产品推荐

