简体   繁体   中英

Can I make a computed string type in Typescript?

For example:

type EventName = "abort" | "afterprint" | "animationend"; //html event names.
type EventListenerPropertyName = "on" + EventName;

I want to create an EventListenerPropertyName from EventName (like this: "on" + "click" => "onclick" ), but TypeScript looks like it doesn't support plus operator between types. How can I make it work?

You can't but you can do it differently. I always use for such - tuple types. Consider:

type EventName = "abort" | "afterprint" | "animationend"; //html event names.
type EventListenerPropertyName = ["on" , EventName];

// example value
const x: EventListenerPropertyName = ['on', 'abort']

What you have is some kind of join of two types as you would in a form of string concatenation. We can also go further and introduce some generic types and value constructors. Consider:

type EventName = "abort" | "afterprint" | "animationend"; //html event names.
type EventListenerPropertyName<T extends EventName>  = ["on", T];

// value constructor
const makeEventListenerPropertyName = <T extends EventName>(a: T): EventListenerPropertyName<T> => ["on", a];
// parser to string
const eventListenerPropertyNameStr = <T extends EventListenerPropertyName<any>>(a: T): string => a[0] + a[1];

const x = makeEventListenerPropertyName('abort'); // x is ['on', 'abort']
const y = eventListenerPropertyNameStr(x); // y is onabort

Typescript 4.1 now supports template literal string types , so you can do:

type EventName = "abort" | "afterprint" | "animationend"; //html event names.
type EventListenerPropertyName = `on${EventName}`;

If you want to capitalize the first letter of each event, so that you have something like onAbort , you can use Capitalize from the builtin template literal types

type EventListenerPropertyName = `on${Capitalize<EventName>}`;

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