您将如何实现myFunc?
const myObj: {prop: 'hello'} = myFunc('hello');
我可以这样做:
function myFunc<T = string>(value: T): {prop: T} {
return {prop: value};
}
const obj: {prop: 'hello'} = myFunc<'hello'>('hello');
有没有一种方法可以使它在没有<'hello'>的情况下工作?
答案 0 :(得分:1)
Typescript会根据返回类型进行推断,因此,例如T
将被推断为hello:
function myFunc<T>(): { prop: T } {
return null as any;
}
const myObj: {prop: 'hello'} = myFunc(); // T is inferred to hello if we hover in VS Code over the call we can see this.
提出您的问题,尽管我真的不认为这是您要寻找的。如果希望将T
推断为字符串文字类型,则需要指定T extends string
,然后无需指定额外的类型注释:
function myFunc<T extends string>(value: T): { prop: T } {
return null as any;
}
const myObj: {prop: 'hello'} = myFunc('hello'); // T is inffered to hello
const myObj2 = myFunc('hello'); // T is inffered to hello, myObjs2 is typed as {prop: 'hello'} , no types necessary