TypeScript:你能根据函数的参数定义一个返回类型结构吗



我正在尝试创建一个函数,该函数将接受一个字符串参数并返回一个以该字符串为键的对象。

例如(伪代码(:test('bar') => {bar: ...}

我不知道如何为这个函数获得正确的返回类型。

这段代码给了我正确的返回类型,但TS编译器认为我返回的对象与返回类型不匹配?

function test<K extends string>(key: K):{[prop in K]: number} {
return { [key]: 6 } // error: not assignable
}
const foo = test<'bar'>('bar')
// foo type: {bar: number} // return type is good

这样的东西会很好用的。但并没有给我强烈的类型返回类型我正在寻找:

function test2<K extends string>(key: K){
return { [key]: 6 }
}
const foo2 = test2<'bar'>('bar')
// foo2 type: {[x: string]: number}  // no good

如有任何帮助,我们将不胜感激!

稍微调整一下第一次尝试,这似乎奏效了:

function test<K extends string>(key: K) {
return { [key]: 6 } as {[prop in K]: number}
}
const foo = test('bar') // { bar: number }

不过,我觉得必须选演员有点奇怪。

您可以使用扩展打字法做很多事情。

就像@SnailCrusher展示的那样,你可以静态地定义返回类型。还有一种方法可以动态地为返回的道具分配打字员:

// this interface defines potential parameters to the methods
interface Tokens {
foo: number,
bar: string,
}

// return one prop in the result object
// this methods only accept keys of the interface Tokens as valid inputs
function test<K extends keyof Tokens>(key: K) {
switch(key) {
case 'foo': return { [key]: 0 } as {[prop in K]: Tokens[K]}
case 'bar': return { [key]: '0' } as {[prop in K]: Tokens[K]};
}
return { [key]: undefined } as {[prop in K]: Tokens[K]}
}
const bar = test('bar') // { bar: string }
const foo = test('foo') // { foo: number }

// return full interface in the result object
// the given token will be set an all other props will be optional
function test2<K extends keyof Tokens>(key: K) {
return { [key]: 6 } as {[prop in K]: Tokens[K]} & {[P in keyof Tokens]?: Tokens[P];}
}
const bar2 = test2('bar') // { foo?: number; bar: string; }
const foo2 = test2('foo') // { foo: number; bar?: string; }

这将为有效参数的IDE添加丰富的上下文。

您可以在Typescript文档中阅读更多内容:https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-类型和索引签名

我不明白为什么这里需要泛型,什么反对简单地进行

function test(key: string): { [key: string]: number } {
return { [key]: 6 };
}

相关内容

最新更新