4 ms·
Casting can hide errors. It's better to assign it to a variable first that has a type declaration. const dog: Dog = { breed: "Airedale", ag
by felixfbecker 7y ago
Casting can hide errors. It's better to assign it to a variable first that has a type declaration.
const dog: Dog = {
breed: "Airedale",
age: 3
}
printDog(dog)
An IIFE is safe too:
printDog(((): Dog => ({
breed: "Airedale",
age: 3
})())
- BigJono 7y agoYeah and both of those are less readable, and used everywhere add up to a really crap code base relative to the same code in plain JS.
- horseman 7y agoYah, pojs is so much nicer because when you mistype breed as bred you get to debug the issue at runtime for a while changing things that are irrelevant when TS could have told you immediately
- johnghanks 7y agoI would absolutely reject a PR with the IIFE.
- jahewson 7y agoActually this cast is safe in TypeScript, additional variables are unnecessary. The statement ‘const d: Dog’ and the expression ‘d as Dog’ are equivalent w.r.t. type safety. The compiler will error in both cases the if the value is not a Dog.
- agentcooper 7y agoThis is not correct. Following example is valid in strict TypeScript: interface Dog { breed: string; } const dog = {} as Dog; console.log(dog.breed); Using `as` is very unsafe in TypeScript. I've collected more quirks of `as` in this playground: https://www.typescriptlang.org/play/index.html#code/PTAEAMEsGd1AzArgOwMYBdIHtmgLYCGAnqADZZYDW0o0kppRANKAEaLqgrxYBO6KAugCmjUOgAWw3sNAxQyLKADuxcUpkAHXlgAmiVLMjoAUCFAEaBUJsQzxRTbNLCAbqNCoc0dLwOYcADozMABlYVk8PiNkENAJdHRNaAAuEABzYwlEVkCvPGA8SFQdaCx4dGAAFUdhUJLITUqYaERhaGAAdgAWAA4ARgBiFrb8vGFkdABabv6AVgGAZkWABgA2YKQ0ANwYAB4qgD4AClcCUjaU0CqASiuq0ABvE1BQGQFeXDOL4QBuEwAviYTOhaqAAGI4TgAXlAACJSJB0gk4aAAD7w8a6SCIPCojFw1hYUi6OH-EyQSbSeAEQygAAK0jKuGer3gkF4PgAcgRxlcfLxKel-kC4gBJXBuaQkVCWWTKKS4cCWOA0+g0dBKWXoVASCy4LCsVzYRAasHSHS8JhxKCwGw6fSGGi6doc4S6NjCCQEY18YKoUiWGgAYSeL1o6CEslhrNetH6AH1LFdHgCLDRGZycNa4-GEzArvtM8yTqmbtbw69oAAmJOpUAAbQRSJRLDhynQ8DhAF106AAIK8XjEPaQyaHHNxmv5+v7MfoBvdk5NxHI9Bwtsdrvd8vA3PQRZ1q7tzuoywQqGTquHgtyaCjqEnE9dm7hgEikxAA https://www.typescriptlang.org/play/index.html#code/PTAEAMEs...