TypeScript: Define a union type from an array of strings

前端 未结 2 1537
广开言路
广开言路 2020-12-24 12:06

I can\'t be the first person coming across this, but my searches have not turned up any useful leads yet. Would greatly appreciate some expert TypeScript advice.

Say

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 12:41

    TypeScript 3.4 added const assertions which allow for writing this as:

    const fruits = ["Apple", "Orange", "Pear"] as const;
    type Fruits = typeof fruits[number]; // "Apple" | "Orange" | "Pear"
    

    With as const TypeScript infers the type of fruits above as readonly["Apple", "Orange", "Pear"]. Previously, it would infer it as string[], preventing typeof fruits[number] from producing the desired union type.

提交回复
热议问题