Day12: Learning TypeScript: Literal Types / Tuple
Today we will introduce Literal Types (字面值型別) and Tuples (元組).
Day12: Learning TypeScript: Literal Types / Tuple
Literal Types (字面值型別)
String Literal Types
String literal types are a way to represent specific values as types, restricting the value to one of a few specific strings. For example, we can make the literal value of variable x equal to "hello".
let x: "hello" = "hello";
x = "hello"; //ok
x = "howdy"; //Type '"howdy"' is not assignable to type '"hello"'But it is rare to have a variable with only one value. We can combine desired values, such as giving alignment three literal values, where the parameter must match one of them. If it does not match one of these three values or is misspelled, it will throw an error.
function printText(s: string, alignment: "left" | "right" | "center") {
console.log(`${s} placed at the ${alignment}`)
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
//error: Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.Numeric Literal Types
Similarly, numeric operations can also be restricted:
The return value of the compare function can only be -1, 0, or 1.
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}Non-Literal Types
Non-literal types can also be combined:
interface Options {
width: number;
}
function configure(x: Options | "auto") {
console.log(x);
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // Does not match Options and "auto"
//error: Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.Tuples (元組)
Tuples are a combination of different types of objects. For example, we can define a tuple with a string and a number:
const iris: [string, number] = ['iris', 18];You can use and assign values to the properties of the types. However, when initializing or assigning a tuple type variable, all items must be provided. Adding items of different types is also not allowed:
let tom: [string, number];
tom = ['tom', 18]; // If tom is only declared without assignment, it will be undefined, and if tsconfig strictNullChecks is enabled, it will throw an error.
tom[0] = 'Tom'; //ok
tom[1] = 25; //ok
tom[0].slice(1); //ok
tom[1].toFixed(2); //ok
tom.push('male'); //ok
tom = ['tom chen']; //error: Property '1' is missing in type '[string]' but required in type '[string, number]'.
tom.push(true); //error: Argument of type 'true' is not assignable to parameter of type 'string | number'.This is a test example while learning, feel free to refer here.
Thank you for reading, see you tomorrow!
References
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types https://willh.gitbook.io/typescript-tutorial/advanced/tuple
Related Posts
Day30 :I finally finished!
I finally finished! Recently, I went to draw, and here is a drawing of "The Little Prince and the Fox." My favorite part of "The Little Prince" is their story. Drawing is really therapeutic, just like the feeling of finishing this challenge.
Day29 :TypeScript Learning : React + TypeScript Todo App Part2
Continuing with the Todo app part 2, I will document the issues encountered during the implementation.
Day28 :TypeScript Learning : React + TypeScript Todo App Part1
After taking so many notes, it's finally time to implement a simple to-do app and document the issues encountered during the implementation.