为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

largeQ 2023-03-24 16:38:06
我正在尝试创建一个函数,它将接受一个字符串参数并返回一个以该字符串为键的对象。例如(伪代码): 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对此的任何帮助将不胜感激!
查看完整描述

3 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

你可以用扩展类型做很多事情。


正如@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-types-and-index-signatures


查看完整回答
反对 回复 2023-03-24
?
浮云间

TA贡献1829条经验 获得超4个赞

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


function test<K extends string>(key: K) {

  return { [key]: 6 } as {[prop in K]: number}

}


const foo = test('bar') // { bar: number }

不过,不得不施放它对我来说似乎有点奇怪。


查看完整回答
反对 回复 2023-03-24
?
萧十郎

TA贡献1815条经验 获得超12个赞

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


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

  return { [key]: 6 };

}


查看完整回答
反对 回复 2023-03-24
  • 3 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信