是否可以获取对象特定属性的静态数组的文字字符串联合类型?
例如,我想公开IconName
为一种文字字符串类型,可以从对象数组中推断出该文字字符串。
我已经看到已经将只读数组转换为字符串文字联合,但不是通过对象数组。
我认为这是不可能的,因为我们需要一些运行时解释功能来访问数组的值。但这是我试图完成这个简洁示例的示例https://codesandbox.io/s/svelte-typescript-forked-ef75y:
<script lang="ts">
interface Icon {
name: string
color: string
}
const icons: readonly Icon[] = <const>[
{
name: "close",
color: "red"
},
{
name: "open",
color: "blue"
}
];
const tuple = <K extends string[]>(...arr: K) => arr;
const iconNames = tuple(...icons.map(i => i.name));
type IconName = typeof iconNames[number];
export let name: IconName;
let displayIcon = icons.find((e) => e.name === name);
</script>
<h1>{displayIcon.color}</h1>
Run Code Online (Sandbox Code Playgroud)