This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

TypeScript Examples (26)

TypeScript type assertionsCopy the code

Types of assertions

Type Assertion manually specifies the Type of a value.

Syntax: Value as type or < type > value

/ / 1
function getLength(name: string | number) {
    return name.length;
}
Copy the code

Error: the Property ‘length’ does not exist on the type ‘string | number’.

The reason for the error is that the value of parameter name may be of type number, and the value of type number does not have the length attribute. In this case, we need to use type assertion to handle the error.

<>

/ / 2
function getLength(name: string | number) {
    return (<string>name).length;
}
console.log(getLength('abc'));  / / 3
console.log(getLength(20));     // undefined
Copy the code

Grammar 2: As

/ / 3
function getLength(name: string | number) {
    return (name as string).length;
}
Copy the code

The result of grammar two is the same as that of grammar one.

Type assertion only takes effect at compile time, and type assertion statements are removed at compile results. So it’s not a cast and it doesn’t really affect the type of the variable.

Assert a union type as one of the types.

Sometimes we really need to access properties or methods that are specific to one of the types without determining the type, such as type protection through type assertion.

/ / 4
/ / declare the interface
interface Teacher {
    name: string;
    profession: 'teacher';
    teach: () = > {};
}
interface Dancer {
    name: string;
    profession: 'dancer';
    dance: () = > {};
}

function work(person: Teacher | Dancer) {
    if (person.profession === 'teacher') {
        // If person's profession is a teacher, we assert to TypeScript that person is a teacher
        (person as Teacher).teach()
    } else {
        (person as Dancer).dance()
    }
}
Copy the code
Assert a parent class as a more concrete subclass
/ / case 5
class ApiError extends Error {
    code: number = 0;
}
class HttpError extends Error {
    statusCode: number = 200;
}

function isApiError(error: Error) {
    if (error instanceof ApiError) {
        return true;
    }
    return false;
}
Copy the code

A more appropriate way to determine ApiError in Example 5 is to use instanceof.

Assert any type as any
/ / case 6
window. Name = 'XXX';Copy the code

Sometimes you need to add a Property to a window, such as name, but TypeScript compiles an error: Property ‘name’ does not exist on type ‘window’.

If the name attribute does not exist on the window, we can temporarily declare the window to be of type any using as any:

/ / case 7
(window as any).name = 'xxx';
Copy the code

The assertion of a type to any does have some usefulness, but be careful not to overuse it.

Matters needing attention

Type assertions can only be checked by the compiler and cannot avoid runtime errors, so abuse of type assertions at development time can lead to runtime errors. Because JSX syntax includes Angle brackets <>, TypeScript disables type assertions using Angle brackets in.tsx files. Type assertions use as syntax.

Finish this! If this article helps you at all, please give it a thumbs up.