Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active May 6, 2019 10:28
Show Gist options
  • Save uladzislau-stuk/6d6183363396df84aafd52c020b35f2d to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/6d6183363396df84aafd52c020b35f2d to your computer and use it in GitHub Desktop.
[Basic Types] #typescript

Basic Types

// array
let arr: any[] = [1, true, 'false', {}]
arr[1] = 100
// TypeScript comes with a ReadonlyArray<T> type that is the same as Array<T> with all mutating methods removed, so you can make sure you don’t change your arrays after creation
let arr2: number[] = [1, 2, 3]
let ro: ReadonlyArray<number> = a
a = ro; // error!
a = ro as number[] // OK
// tuple
let x: [string, number]
x = ["hello", 10]
// x[3] = "world" ? Why error
// enum
enum Color { Red = 1, Blue = 2 }
let c: Color = Color.Red
let colorName: string = Color[1]
// void
let v1 = (): void => console.log('it\'s type void')
let v2: void = null || undefined
// null and undefined
let u: undefined = undefined
let n: null = null
// never - function or () => that always return exception or one that never return
let error = (message: string): never => {
throw new Error(message)
}
let fail = () => error('Smth failed!')
// object
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
// type assertion
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length
let strLength2: number = (someValue as string).length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment