【问题标题】:How to get a literal type from a function argument for a computed property name?如何从计算属性名称的函数参数中获取文字类型?
【发布时间】:2021-07-10 08:03:12
【问题描述】:

请考虑以下代码:

const fn = (name: string) => {
  return { [name]: "some txt" };
};

const res = fn("books"); // books or any other string

TS 将res 识别为以下类型:

const res: {
  [x: string]: string;
}

我想让 TS 知道 res 有一个属性 books

const res: {
  books: string;
}

我尝试了很多东西,但似乎没有任何效果。 有可能吗?这是一个已知问题吗?

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    你必须像这样创建一个通用函数:

    const fn = <T extends string>(name: T): { [key in T]: string } => {
      return { [name]: "some txt" } as any;
    };
    
    const res = fn("books");
    

    这似乎是 TypeScript 中的一个错误,它不允许这样的事情,这就是你需要as any 的原因。有关交互式示例,请参阅 here。

    【讨论】:

    猜你喜欢
    • 2021-07-10
    • 2021-12-04
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    相关资源
    最近更新 更多