Viki

Viki 写东西的地方

努力上进且优秀
github
email
x
steam
bilibili
douban

Enable autocompletion for the TS type "cat" | string.

Problem Description#

Examine the following TS types.

type Animal = "cat" | "dog" | string;

Normally, we might write it like above, but this doesn't provide good autocomplete suggestions in vscode.

const animal: Animal = ''; // No autocomplete suggestions after typing the quotes

Solution#

To solve this problem, we can use the following two approaches.

// Approach 1: Use `string & {}` instead of `string`
type Animal = "cat" | "dog" | (string & {});

// Approach 2: Use Omit to manually exclude types from `string`
type Animal = "cat" | "dog" | Omit<string, "cat" | "dog">

const animal: Animal = ''; // After typing the quotes, you can see the correct autocomplete suggestions

Result#

Before (No autocomplete suggestions)#

image

After (Improved autocomplete suggestions)#

image

image

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.