繁体   English   中英

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

[英]TypeScript: Can you define a return Type structure based on an argument of the function?

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

例如(伪代码): 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 所示,您可以静态定义返回类型。 还有一种方法可以为返回的 props 动态分配类型:

 // 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-types-and-index-signatures

我不明白为什么你在这里需要泛型,什么反对简单地做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM