简体   繁体   中英

Enforce altering string adheres to Typescript type union

I have a library that requires a type like:

type Strings = "A" | "B"

Sometimes I will get a simple string like "A" or "B", other times I get something like "summedA" or "summedB". If alter the string, how can I convince typescript that I will make sure I format it correctly? For example:

functionThatRequiresType(input: Strings) {...}

const string: string = "summedA"

const newString = string.replace("summed", "")

functionThatRequiresType(newString) => calling throws error

You can tell TypeScript that string.replace("summed", "") returns a value of type Strings using as .

Example :

type Strings = "A" | "B"

function functionThatRequiresType(input: Strings) {}

const string: string = "summedA"

const newString = string.replace("summed", "") as Strings

functionThatRequiresType(newString)

You can use type casting:

const newString = string.replace("summed", "") as Strings

However, doing this might weaken the type system as TypeScript will believe that your type casting is right most of the time.

Thus, you have to use type casting cautiously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM