如何从计算属性名称的函数参数中获取文字类型? [英] How to get a literal type from a function argument for a computed property name?

查看:23
本文介绍了如何从计算属性名称的函数参数中获取文字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

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

TS 将 res 识别为以下类型:

TS recognizes res as the following type:

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

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

I'd like TS to know that res has a property books

const res: {
  books: string;
}

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

I tried many things but nothing seems to work. Is it possible at all? Is it a known issue?

推荐答案

你必须像这样创建一个泛型函数:

You have to create a generic function like this:

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

const res = fn("books");

这似乎是 TypeScript 中的一个错误,它不允许这样的事情,这就是为什么你需要 as any.请参阅此处交互示例

It seems like a bug in TypeScript that it doesn't allow such things, that's why you need the as any. See here for an interactive example.

这篇关于如何从计算属性名称的函数参数中获取文字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆