News for hackers. Stuff that matters.
Re:TypeScript’s quirks: How inconsistencies make the languag... by mekster on Friday January 31, 2020 @08:22PM (#22207824)
Casting is as bad as using "any". You can make the compiler think anything you throw at it as that type and you can get bitten at runtime.
Re:TypeScript’s quirks: How inconsistencies make the languag... by alexcole on Friday January 31, 2020 @08:49PM (#22207968)
Thats not 100% true in TypeScript. TypeScript actually only allows "up-casts" and "down-cast" (but if the type is neither a supertype nor a subtype the compiler will throw an error).
Re:TypeScript’s quirks: How inconsistencies make the languag... by seanmcdirmid on Friday January 31, 2020 @10:16PM (#22208400)
Ya, I often have to write “this as any as T” because I’m using T as a self type.
Re:TypeScript’s quirks: How inconsistencies make the languag... by nojvek on Friday January 31, 2020 @09:52PM (#22208292)
That’s my understanding too. You just can’t cast types wily Nily.
Re:TypeScript’s quirks: How inconsistencies make the languag... by jahewson on Saturday February 01, 2020 @12:08AM (#22208820)
Nope. This is not how casting works in TypeScript. To get an unsafe cast you have to go via the ‘any’ or ‘unknown’ types.

e.g.

‘foo as unknown as Dog’

Re:TypeScript’s quirks: How inconsistencies make the languag... by okbake on Saturday February 01, 2020 @03:15PM (#22212943)
There are a few casts that are allowed that I would consider unsafe, particularly around unions of literals or using empty object literals:

  // No error here
  type Animal = 'dog' | 'cat';
  const notAnimal = 'couch' as Animal;

  // No error here either
  type Food = { isSpicy: boolean };
  const empty = {} as Food;

https://www.typescriptlang.org/play/index.html#code/C4TwDgpg...