Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It may be string comparison on the JS level.

However If it is string comparison on the TS level then that means it isn't type checked. Are you sure this is what you mean? That means I can add a new case for string "asdasfsdfds" and TS won't throw a type error.

The variant type is not exclusively an FP paradigm.



If you hover over 'action.type' in the switch statement, you will see

  (property) type: "AddMovie" | "RemoveMovie" | "Reset"
So you can't add a new case because while the value is a JS string, the type is a restricted subset of string i.e. a union of only 3 possible string constants.

Therefore you are right - its not quite a string at the TS level - its a subset of string.

p.s. you can make unions of any primitive values in TypeScript:

  let a:3 | "hello" | true = 3;
  a = "hello"; // valid
  a = true; // valid
  a = false; // not valid!
or between any type and other values, really:

  let a: number | 'NotNumber' = 0;
  a = 1; // ok
  a = a - 1; // still ok, assignment narrowed the type to number
  a = 'NotNumber' // ok
  a = a - 1; // error! narrowed the type to the constant 'NotNumber', can't subtract anymore
  a = 'Hi' // ERROR
TS is not always that smart about it (compared to Flow), but sometimes it works out quite well :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: