0

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);
ChrisRich
  • 8,300
  • 11
  • 48
  • 67
  • 2
    Same thing. `as` was introduced so the former wasn't confused for a JSX tag. – kelsny Sep 22 '22 at 02:06
  • 1
    You probably mean _angle_ brackets (`<>`). Square brackets normally refer to `[]` like for arrays. – ghybs Sep 22 '22 at 02:15
  • 1
    Does this answer your question? [Any difference between type assertions and the newer \`as\` operator in TypeScript?](https://stackoverflow.com/questions/33503077/any-difference-between-type-assertions-and-the-newer-as-operator-in-typescript) – Tobias S. Sep 22 '22 at 02:21

1 Answers1

3

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)
dineshpandikona
  • 620
  • 4
  • 17