如何从计算的 属性 名称的函数参数中获取文字类型?

How to get a literal type from a function argument for a computed property name?

请考虑以下代码:

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;
}

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

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

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