我能做这些
const keys = {
"hi": {name: "ho"}
}
type U = [keyof typeof keys][0]; // "hi"我能对数组的值也这样做吗?
const data = [
{ name: "hi" }
];
type T = typeof data[0]["name"]; // string not "hi"发布于 2020-06-15 17:40:15
只需将as const添加到您的数据:
const data = [
{ name: "hi" }
] as const;如果没有as const,数据将被推断为Array<{name: string}>。keys不需要as const,因为它是推断出的{hi: {name: string}}
发布于 2020-06-15 17:49:48
因为数组的元素可以在运行时更改,所以TS只会将数据类型推断为Array<{ name: string }>。您必须显式地将data数组的类型设置为readonly,这样TS才能推断出数据数组中第一个元素的类型为{name: "hi"}。
解决方案是只将as const添加到数据数组中。
const data = [
{name: "hi"}
] as const;
// this will make TS infer the type for data as readonly[{ readonly name: "hi";}]查看ts playground中的演示
https://stackoverflow.com/questions/62385337
复制相似问题