01 - Basic Types
TypeScript Basic Types
Boolean
let isDone: boolean = false;
Number (can also use hex, binary, octal)
- can also use hex, binary, octal
let decimal: number = 6;
String
- can use single or double quotes and template strings
let color: string = 'blue';
Array
First way of declaring array type
let list: number[] = [1, 2, 3];
Second way of declaring array type
- uses a generic array type,
Array<elemType>
let list: Array<number> = [1, 2, 3];
Tuple
- allows you to express an array where the type of a fixed number of elements is known, but need not be the same
- when accessing an element outside the set of known indices, a union type is used instead, this means that the third element can be assigned to a string or number
let x: [string, number];
x = ['hello', 10]; // ok
x = [10, 'hello']; // error
Enum
- a way of giving more friendly names to sets of numeric values
- by default numbering begins at 0, can be changed with
{Red = 1}
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
Any
- a way of describing the type of variables that we don't know the values of, may come from dynamic content i.e. user-input
let notSure: any = 4;
Void
- the absence of having any type at all, could be a return type of functions
- declaring variables of type void is not useful because you can only assign undefined or null to them
Null
let n: null = null;
Undefined
let u: undefined = undefined;
Never
- represents the type of values that never occur e.g. never is the return type for a function expression or arrow function that always throws an exception
function error(message: string) : never {
throw new Error(message);
}
Object
- represents the non-primitive type
declare function create (o: object | null): void;
Type Assertions
- a way to tell the compiler "trust me, I know what I'm doing"
- when using TypeScript with JSX, only as-style assertions are allowed
First form:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Second form:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;