首页 > 解决方案 > 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

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

标签: javascripttypescripttypescript-generics

解决方案


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

就像@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


推荐阅读