Typescript types
Ce contenu n’est pas encore disponible dans votre langue.
Primitive types
Section titled “Primitive types”// booleanlet isCool: boolean = false
// numberlet age: number = 56
// stringlet eyeColor: string = 'brown'let favoriteQuote: string = `I'm not old, I'm only ${age}`
// null and undefinedlet meh: undefined = undefinedlet noo: null = nullComplex types
Section titled “Complex types”// Arraylet pets: string[] = ['cat', 'mouse', 'dragon']let pets2: Array<string> = ['pig', 'lion', 'dragon']
// Tuplelet basket: [string, number]basket = ['basketball', 10]
// Enumenum Size { Small = 1, Medium = 2, Large = 3,}let sizeName: string = Size[2]alert(sizeName) // Displays 'Medium' as its value is 2 above
type animals = 'cat' | 'mouse' | 'dragon'
// Anylet whatever: any = 'aaaaghhhhhh noooooo!'
// voidlet sing = (): void => console.log('Lalalala')
// neverlet error = (): never => { throw Error('blah!')}
// Type Assertionlet ohHiThere: any = 'OH HI THERE'let stringLength: number = (ohHiThere as string).length
interface CatArmy { count: number type: string}
let dog = {} as CatArmydog.count = 5
// Interfaceinterface RobotArmy { count: number type: string magic?: string}
let fightRobotArmy = (robots: RobotArmy): void => { console.log('FIGHT!')}let fightRobotArmy2 = (robots: { count: number type: string magic?: string}): void => { console.log('FIGHT!')}
// Functionlet fightRobotArmyF = (robots: RobotArmy): void => { console.log('FIGHT!')}let fightRobotArmy2F = (robots: { count: number type: string magic?: string}): void => { console.log('FIGHT!')}
// *** Classclass Animal { constructor(private sound: string) {} greet(): string { return 'Hello, ' + this.sing }}
let lion = new Animal('Lion')lion.greet() // Displays 'Hello, Lion'
//In TypeScript, there are several places where type inference//is used to provide type information when there is no explicit//type annotation. For example, in this codelet x = 3// automatically detects x is a number.
// Union Typelet confused: string | number = 'hello'