Last active
February 21, 2020 15:54
-
-
Save GerardKetuma/df051ec9199eca020b5966ab5194d0a5 to your computer and use it in GitHub Desktop.
Basic types in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See blog post at https://ketuma.com/lessons/typescript-basic-types | |
//Boolean | |
const isOdd: boolean = true | |
const isEven: boolean = false | |
//Number | |
const fibonacci: number = 34 //decimal | |
const color: number = 0xbada55 //hexadecimal | |
const adder: number = 0b1011 //binary | |
const chmod: number = 0o755 //octal | |
//String | |
const firstName: string = "John" | |
const lastName: string = 'Smith' | |
const fullName: string = `${ firstName } ${ lastName }` // John Smith | |
//Array | |
const fibonacci: number[] = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | |
const faang: Array<String> = ['Facebook', 'Amazon', 'Apple', 'Netflix', 'Google'] | |
//Tuple | |
let streetName: [number, string] = [322, 'HighWay Dr.'] | |
console.log(streetName[0]) // 322 | |
console.log(streetName[1]) // HighWay Dr. | |
streetName = ['HighWay Dr.', 322] // Error | |
//Enum | |
enum StateTrinity { Loading, Success, Error } | |
const ajaxCall: StateTrinity = StateTrinity.Success | |
const enumName: string = StateTrinity[2] | |
console.log(enumName) // Displays 'Error' | |
//Any | |
let ajaxResponse: any = { x: 20, y: 30, z: 40} | |
ajaxResponse = 'This is an error' | |
ajaxResponse = true | |
const random: any[] = ['House', 24, 'Roof', {x: 1, y: 2}] | |
//Void | |
function logOutput(): void { | |
const message: string = receiveValueFromApi() | |
console.log(message) | |
} | |
//Null and Undefined | |
let salary: number | null = 345000 | |
salary = null // This is valid because null is part of the type. | |
//Never | |
// Inferred return type is never | |
function divideByZero(num: number) { | |
throw new Error('We cannot divide by zero') | |
} | |
//Object | |
function parseObject(obj: object | null): void { | |
console.log(obj) | |
} | |
parseObject({x: 10, y: 20, z: 30}) // OK | |
parseObject(null) // OK | |
parseObject(322) // Error | |
parseObject(true) // Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment