[Typescript] Tips: Create autocomplete helper which allows for arbitrary values

Ever wanted just a bit of autocomplete? Here, we create a TypeScript helper called LooseAutocomplete which gives us autocomplete while also allowing arbitrary values.

 

We want IconSize to be "sm" | "xs" or any other string value, but we cannot do like this:

type IconSize = "sm" | "xs" | string

This will be IconSize just be string. And we lost autocomplete.

 

The way we can do:

type IconSize = LooseAutoComplete<"sm" | "xs">
type LooseAutoComplete<T extends string> = T | Omit<string, T>

 

posted @ 2022-10-10 14:17  Zhentiw  阅读(17)  评论(0编辑  收藏  举报