Home > Mobile >  TypeScript casting angle brackets vs regular casting
TypeScript casting angle brackets vs regular casting

Time:09-22

In terms of TS type casting using below Tuple type as example, is there any significant difference between #1 and #2?

Declaring type Tuple:

type Tuple = [string, string];

#1 Using square brackets before the function argument

myFunction(<Tuple>value);

#2 Regular type casting

myFunction(value as Tuple);

CodePudding user response:

Well, It is type assertion not type casting. The difference is you cannot use <type> syntax in .tsx files as the compiler will infer it as an JSX element with no corresponding closing tag. SO, it is preferred to use as way of type assertion as it works everywhere.

//if this function is in 'tsx' file, compiler gives errror
myFunction(<Tuple>value); 

//this works everywhere as intended
myFunction(value as Tuple)
  • Related