PresentProgrammer
PresentProgrammer

Reputation: 703

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

What should be put in place of ??? so that the following would work:

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

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

Upvotes: 0

Views: 64

Answers (1)

VLAZ
VLAZ

Reputation: 29009

You can use the $Keys utility type that will extract all keys from a type and produce a union of them.

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

In effect $Keys<Product> is the same as "id" | "name" but it's dynamically calculated based on the properties present in Product. You can also extract the type if you want to re-use it a lot:

type ValidKey = $Keys<Product>

const foo: ValidKey = "id"

Upvotes: 3

Related Questions