如何为带泛型的函数使用ReturnType并指定泛型类型?
TypeScript泛型ReturnType指定具体类型的问题
问题代码
function foo<T>(init: T) { let data = init; return { getData: () => data, update: (u: T) => { data = u } } } let obj: ReturnType<typeof foo>; obj = foo<boolean>(true); // 报错
错误信息
Type '{ getData: () => boolean; update: (u: boolean) => void; }' is not assignable to type '{ getData: () => unknown; update: (u: unknown) => void; }'. Types of property 'update' are incompatible. Type '(u: boolean) => void' is not assignable to type '(u: unknown) => void'. Types of parameters 'u' and 'u' are incompatible. Type 'unknown' is not assignable to type 'boolean'.
问题原因
let obj: ReturnType<typeof foo>;里没有给泛型函数foo指定具体的类型参数T,TypeScript会自动将T推断为unknown,导致obj的类型被定为包含unknown的返回结构,和foo<boolean>(true)返回的boolean类型结构不兼容。
解决方案:直接在ReturnType中指定泛型类型
当然可以直接在ReturnType<typeof foo>里指定T的具体类型,只需要给typeof foo手动传入泛型参数即可,写法如下:
function foo<T>(init: T) { let data = init; return { getData: () => data, update: (u: T) => { data = u } } } // 直接给typeof foo指定泛型参数boolean let obj: ReturnType<typeof foo<boolean>>; obj = foo<boolean>(true); // 不再报错
这样obj的类型就会被正确推断为{ getData: () => boolean; update: (u: boolean) => void; },和foo<boolean>(true)的返回类型完全匹配,赋值时就不会有类型错误了。
内容的提问来源于stack exchange,提问作者Jeanluca Scaljeri
相关产品推荐
相关产品推荐

