TypeScript- base type assertion -08-

Type assertion

Assertion type (Type Assertion) may be used to specify the type of a value manually.

grammar

<类型>值

or

值 as 类型

Must be used tsx syntax (React syntax of jsx ts version) in the latter.

Example: a joint type variable is specified as a more specific type

I mentioned earlier , when a joint TypeScript uncertain variable of type in the end is what type, we can only access the properties or methods common to all types of this union type in :

function getLength(something: string | number): number {
    return something.length;
}

// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.

And sometimes, we do need to access one type of property or method does not determine the type of the time, such as:

function getLength(something: string | number): number {
    if (something.length) {
        return something.length;
    } else {
        return something.toString().length;
    }
}

// index.ts(2,19): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.
// index.ts(3,26): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.

In the above example, access something.lengthtime error.

Type may be used at this time asserted, the somethingassertion into string:

function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}

Type of usage assertion above, before the variables that need to add assertions <Type>can be.

Type type conversion is not asserted, the assertion into a type union type that does not exist is not allowed :

function toBoolean(something: string | number): boolean {
    return <boolean>something;
}

// index.ts(2,10): error TS2352: Type 'string | number' cannot be converted to type 'boolean'.
//   Type 'number' is not comparable to type 'boolean'.

Guess you like

Origin www.cnblogs.com/idspring/p/11784711.html