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

对此的任何帮助将不胜感激!


largeQ
浏览 108回答 3
3回答

喵喵时光机

你可以用扩展类型做很多事情。正如@SnailCrusher 所示,您可以静态定义返回类型。还有一种方法可以动态地将类型分配给返回的道具:// this interface defines potential parameters to the methodsinterface Tokens {&nbsp; &nbsp; foo: number,&nbsp; &nbsp; bar: string,}// return one prop in the result object// this methods only accept keys of the interface Tokens as valid inputsfunction test<K extends keyof Tokens>(key: K) {&nbsp; &nbsp; switch(key) {&nbsp; &nbsp; &nbsp; &nbsp; case 'foo': return { [key]: 0 } as {[prop in K]: Tokens[K]}&nbsp; &nbsp; &nbsp; &nbsp; case 'bar': return { [key]: '0' } as {[prop in K]: Tokens[K]};&nbsp; &nbsp; }&nbsp; &nbsp; 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 optionalfunction test2<K extends keyof Tokens>(key: K) {&nbsp; &nbsp; 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 文档中阅读更多内容:&nbsp;https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types-and-index-signatures

浮云间

稍微调整一下第一次尝试,这似乎有效:function test<K extends string>(key: K) {&nbsp; return { [key]: 6 } as {[prop in K]: number}}const foo = test('bar') // { bar: number }不过,不得不施放它对我来说似乎有点奇怪。

萧十郎

我不明白为什么你在这里需要泛型,这与简单地做相反function test(key: string): { [key: string]: number } {&nbsp; return { [key]: 6 };}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript