What is the difference between using the colon and as syntax for declaring type?

前端 未结 2 1095
清酒与你
清酒与你 2020-12-19 06:26

What is the difference between the : syntax for declaring type

let serverMessage: UServerMessage = message;

and the as

2条回答
  •  萌比男神i
    2020-12-19 07:05

    Yes they are different

    Firstly, let's see this example

    let a: string;
    let b: number;
    
    function c() {
        const d = (a || b) as number; // Works
        const e: number = (a || b); // Throw typing error
    }
    

    so as number telling Typescript that in that case, the value will be a number (define the type of the result). It forces Typescript to think that it will always return a number (even that it could be not true).

    ``: number``` define the type of the variable, not the result. So Typescript will verify and ensure that there could not be another case (Even that it could never happen).

    Hope that help.

提交回复
热议问题