打字稿:是否可以从参数值推断返回值?
Typescript: Is it possible to infer returned value from argument value?
你会如何实现 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'> 的情况下工作?
Typescript 将根据 return 类型进行推断,因此例如此处 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
你会如何实现 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'> 的情况下工作?
Typescript 将根据 return 类型进行推断,因此例如此处 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