TypeScript: Type Basics
Type declaration syntax
- The first thing you shoud do is add types to function parameters.
- This is the most useful.
function f(x: type): type {}
Example. function
function add(a: number, b: number): number { return a + b; } console.log(add(1, 2)); // 3
// arrow function const add_af = (a: number, b: number): number => a + b; console.log(add_af(1, 2)); // 3
Primitive types
stringnumberbooleansymbol
function f(x: number): number { return x + 1; } console.log(f(3)); // 4 function sayhi(x: string): string { return `hi ${x}`; } console.log(sayhi("john")); // hi john
function fa(x: bigint): bigint { return x + 1n; } console.log(fa(2379885977783215527870711291n)); // 2379885977783215527870711292n
Other special types
anyunknown
Array type
type[]
const xx: number[] = [3, 4, 5]; console.log(xx); // [ 3, 4, 5 ]
const joinString = (...xstrings: string[]): string => ("".concat(...xstrings)); console.log(joinString("a", "b", "c")); // abc
Tuple type
[type,type,etc]
// vector addition function ff( [a1, a2]: [number, number], [b1, b2]: [number, number], ): [number, number] { return [a1 + b1, a2 + b2]; } console.log(ff([1, 2], [3, 4])); // [ 4, 6 ] // arrow function const gg = ( [a1, a2]: [number, number], [b1, b2]: [number, number], ): [number, number] => [a1 + b1, a2 + b2]; console.log(gg([1, 2], [3, 4])); // [ 4, 6 ]
Union types
Union Types means one of several.
type | type
can be more than two items.
function ff(x: number | string): number | string { if (typeof x === "number") { return x + x; } else { return x + x; } } console.log(ff(2)); // 4 console.log(ff("a")); // aa
Literal type
number and string can be literal.
let x: "bird" = "bird"; let y: 2 = 2;
literal types are usually used with union:
let id: 0 | 1 = 0; let pets: "cat" | "dog" = dog;
Define type
you can define your own named type.
type TypeName = type
// define a named type. either a number or string type NumOrStr = number | string;
// define a named type. a object that represent coordinate of a point type Point = { x: number; y: number; };
there is also
interface type.
see
Object type
{ name: type; etc }
or
{ name: type, etc }
const vector_add = ( v1: { x: number; y: number }, v2: { x: number; y: number }, ) => { return { x: v1.x + v1.y, y: v2.x + v2.y }; }; console.log( vector_add({ x: 1, y: 1 }, { x: 1, y: 2 }), ); // { x: 2, y: 3 }
Optional property
add a question mark to the end of variable name.
{ name?: type; etc }
Promise type
async function getFavoriteNumber(): Promise<number> { return 26; }
Make immutable data
keyword readonly
readonly is shallow. not content of object.
type t_point { readonly x: number; readonly y: number; }