4 ms·
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.
by mekster 7y ago
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.
- alexcole 7y agoThats 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).
- nojvek 7y agoThat’s my understanding too. You just can’t cast types wily Nily.
- seanmcdirmid 7y agoYa, I often have to write “this as any as T” because I’m using T as a self type.
- jahewson 7y agoNope. 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’
- okbake 7y agoThere 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/C4TwDgpgBAggdgSwLYEMA2UC8UDkATAewHMcoAfXAYxWFIpwCMIUAnHAbgChOB6HqAGII4ETpQJwAzsCgAPAFyxEqDNnzEOvfgFEWLAiygpJUCLMiVgEPGInSoIRfGTosVAgFdKAC018oAHIEpnoGUAweMh5SKABmouJSMgBebjjiXr5GJs4qXFoAtEXFJaVl5RUF3MJWLLEolNACBAR4UADenFBQwkQs1ggQcMCSitIsvQDaALpcAL7c-kIitklQYAjJySiKza1u7T1wfQNDI4qTOJIoXhA4ADS4kGCQ+og401BzXP66+obGUzmCCWayrew+BBoBC7FptbDtb5aQLBCChQwRKIxeLgmRgYzAFAHObZQRw9hAA https://www.typescriptlang.org/play/index.html#code/C4TwDgpg...