我正在尝试从对象数组的属性派生联合类型:
interface Tool {
readonly id: string
}
const tools = [
{id: "foo"},
{id: "bar"},
] as const
function doTheThing<T extends typeof tools>(id: T[number]["id"]) {}
doTheThing("foo") // should work
doTheThing("baz") // should fail
这行得通,因为类型缩小到 foo | bar
但我真正想要的是输入工具对象:
const tools: readonly Tool[] = [
{id: "foo"},
{id: "bar"},
] as const
通过这种方式,我可以对工具对象和函数进行类型检查。如果我将类型添加到工具中,我将不再正确缩小函数参数。