Follow

Follow

String literal type

wang xiao bo 's photo
wang xiao bo
·Aug 31, 2021·

1 min read

The string literal type is used to restrict the value to only one of a few strings.

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // No problem!
handleEvent(document.getElementById('world'), 'dblclick'); // Error, event cannot be'dblclick'

// index.ts(7,47): error TS2345: Argument of type '"dblclick"' is not assignable to parameter of type 'EventNames'.

In the above example, we use type to define a string literal type EventNames, which can only take one of the three strings. Note that both type aliases and string literal types are defined using type.

 
Share this