4 ms·
Actually 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
by jahewson 7y ago
Actually 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...