使用 JavaScript Flow,如何将允许的值限制为键入的键?

With JavaScript Flow, how to limit allowed values to type's keys?

应该用什么代替 ??? 以便以下内容起作用:

type Product = {
    id: number,
    name: string;
}

const foo: ??? = 'id' // works
const bar: ??? = 'name' // works
const baz: ??? = 'someField' // FAIL!

您可以使用 $Keys utility type 从类型中提取所有键并生成它们的并集。

type Product = {
    id: number,
    name: string;
}

const foo: $Keys<Product> = 'id' // works
const bar: $Keys<Product> = 'name' // works
const baz: $Keys<Product> = 'someField' // FAIL!

See a live example

实际上 $Keys<Product>"id" | "name" 相同,但它是根据 Product 中存在的属性动态计算的。如果你想大量重复使用它,你也可以提取类型:

type ValidKey = $Keys<Product>

const foo: ValidKey = "id"