Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

What is the difference between the : syntax for declaring type

let serverMessage: UServerMessage = message;

and the as syntax

let serverMessage = message as UServerMessage;

They seem to produce the same result in this example at least

like image 301
user1283776 Avatar asked Feb 14 '19 07:02

user1283776


People also ask

What is Colon in TypeScript?

Variable Declaration in TypeScriptThe type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. When you declare a variable, you have four options −

What does := means in go?

The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car" The short variable declaration operator( := ) can only be used for declaring local variables.


2 Answers

One is a type annotation one is a type assertion.

The type annotation tells the compiler check that the assignment is fully valid and that message is indeed compatible with UServerMessage

The type assertion tells the compiler, I know what I'm doing, message is a UServerMessage, never mind what you think you know, I have more information and I know best. Some checks are still performed even if you use type assertions so you might see double assertions message as any as UServerMessage for example if the type of message is very incompatible with UServerMessage

You should always prefer a type annotation to an assertion. Use assertion with care and only if you have to. A type assertion is a hammer to get a square peg to fit into a round hole, useful at times but you might take a second look at what you are doing to make sure its right. Make sure it's not:

like image 148
Titian Cernicova-Dragomir Avatar answered Oct 15 '22 22:10

Titian Cernicova-Dragomir


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.

like image 30
Nguyen Phong Thien Avatar answered Oct 15 '22 22:10

Nguyen Phong Thien