I could see that the following code did not trigger any errors or warnings:
type myType = {a:number,b:number}
const myObject = {a:1} as myType
We just had an issue where using "as" caused a production bug, which made me think that there might be an eslint rule that should disallow this. Do you know any such rule?
.eslintrc.json
"@typescript-eslint/consistent-type-assertions": ["warn", {
"assertionStyle": "never"
}],
Yes, type assertion can be really dangerous when used carelessly. No, ESLint does not ship a rule to completely forbid type assertion out of the box. So you'll have to use a custom plugin such as
eslint-plugin-no-type-assertion
Disallow type assertions in TypeScript code. The rule will forbid both as operator and the angle-bracketed syntax, unless used for const assertions or with the unknown type. The rule also forbids non-null assertions.
There are other packages though that offer options to disallow type assertion:
assertionStyle
to "never"
:This option defines the expected assertion style. Valid values for assertionStyle are: as will enforce that you always use ... as foo. angle-bracket will enforce that you always use ... never will enforce that you do not do any type assertions.
Forbids an object literal to appear in a type assertion expression. Casting to any or to unknown is still allowed.
However, I'm not sure if it's a good idea to completely disallow type assertion. There are valid use cases where you really need it. You're minimal, reproducible example is just a severe programmer mistake where basic type security is being ignored.
P. S. type
alias names should be spelled with a Capital by convention (e. g. type MyType = ...
)