Typescript. Type Assertions

as it was mentioned in DataTypes post there are 2 ways of assertions through as and <type> operators

// Type assertions
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
// or
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");

lets look on ascending and descending assertions…

class Person {
    constructor(public name: string) {
        this.name = name;
    }
}

class Employee extends Person {
    constructor(public name: string, public profession) {
        super(name);
        this.profession = profession
    }
}

// more specific assign to more generous

const drHouse = new Employee('Antony', 'doctor');
const person = drHouse;
console.log(person.name);

// more generous assign to more specific with cast

let Stanley: Person = new Employee('Stanley', 'programmer');
let StanleyProgrammer = <Employee>Stanley;
console.log(StanleyProgrammer.profession);
This entry was posted in Без рубрики. Bookmark the permalink.