Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript - string literal type to type string

I have a method with string literal type guard

type Status = 'new' | 'update' | 'close';

itemRequest(status: Status) { 
    itemService.subscribeToChanges(status) //third party library method
}

Difficulty I have is this third party method accepts string not my custom string type Status

subscribeToChanges(status: string) 

How can I make my string literals are actually types of string and when I pass to third party method. It understand it's actually a string?

like image 457
MonteCristo Avatar asked May 02 '26 07:05

MonteCristo


1 Answers

You are able to cast your value of the Status to a string like this:

type Status = 'new' | 'update' | 'close';

itemRequest(status: Status) { 
    itemService.subscribeToChanges(status as string)
}

Do not use String(status). This constructs a new string object from status and is a wasteful allocation. The cast will be erased at runtime and just corrects TypeScript's knowledge of the type of the status variable. Remember that any type checking TypeScript does is done at compile time and has no runtime cost nor presence.

This code will be compiled to the following:

itemRequest(status) {
  itemService.subscribeToChanges(status)
}

I am however confused as to why this is happening. Your type alias are all of type string so casting from Status to string should be a upcast (i.e, permissible under any reasonable type checker). The other way around would be the main issue. Indeed, your original code works just fine on it's own.

like image 62
Dan Avatar answered May 03 '26 20:05

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!