1.

What are string literal types?

Answer»

In TypeScript, you can refer to SPECIFIC strings and numbers as types.

let FOO: "bar" = "bar";// OKfoo = "bar";// Error: Type '"baz"' is not assignable to type '"bar"'.(2322)foo = "baz";

String literal types on their own are not that useful. However, you can combine them into unions. This allows you to specify all the string values that a variable can take, in turn acting like enums. This can be useful for function parameters.

function greet(name: string, GREETING: "hi" | "hello" | "HOLA") {// ...}greet("John", "hello");// Error: Argument of type '"Howdy?"' is not assignable to PARAMETER of type '"hi" | "hello" | "hola"'.(2345)greet("Mary", "Howdy?");

String literal types can help us spell-check the string values. 



Discussion

No Comment Found