by lacker · 6y ago · 0 comments
This is only a problem if you are mixing untyped code with typed code, isn't it? Like when you are parsing JSON, you need to do typechecking right then, rather than just using an "any" type. The only other situation I have run into this in practice with TypeScript is when I'm using a library that has slightly misdefined types.
I find it a bit strange that people talk about this as "only a problem", as though it was some weird niche edge case and not an ever-present issue. The written-in-plain-JS ecosystem completely dwarfs the written-in-TypeScript one; unless you're doing something rather trivial you're quite likely to end up depending on a library that barely had the shape of its objects in mind during development, with typings (if they're even present) that were contributed by someone that's almost definitely not the actual library author.
Of course, if you're competent enough you can correct typings and always remember to run runtime checks on data that doesn't come from you and so on. But it's too easy for a beginner to fall into traps like mishandling data that comes from a dependency (especially when it's buggy/ostensibly has typings) - in my opinion, there should be a first-party compiler/linter option to enforce checks on any `any`.
0. https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...
Moving to Rust doesn't eliminate validation altogether, but you don't have to do any type related validation which is nice.
https://codesandbox.io/s/is849
edit: complete code
```typescript
class Person { id: number; name: string; yearOfBirth: number;
constructor(id: number, name: string, yearOfBirth: number) {
this.id = id;
this.name = name;
if (yearOfBirth < 1900 || yearOfBirth > 2020) {
throw new Error("I don't understand you. Go back to your time machine.");
} else {
this.yearOfBirth = yearOfBirth;
}
}
getAge(): number {
const currentDate: number = new Date().getUTCFullYear();
return currentDate - this.yearOfBirth;
}
}class Dog { id: number; name: string; yearOfBirth: number;
constructor(id: number, name: string, yearOfBirth: number) {
this.id = id;
this.name = name;
if (yearOfBirth < 1947 || yearOfBirth > 2020) {
throw new Error("I don't understand you. Go back to your time machine.");
} else {
this.yearOfBirth = yearOfBirth;
}
}
getAge(): number {
const currentDate: number = new Date().getUTCFullYear();
return (currentDate - this.yearOfBirth) * 7;
}
}const buzz: Person = new Person(1, `Buzz`, 1987);
const airbud: Dog = buzz;
console.log(`Buzz is ${buzz.getAge()} years old.`);
console.log(`Airbud is ${airbud.getAge()} years old in human years.`);
```
[1]: https://codesandbox.io/s/te0pn?file=/index.ts
Edit: Apparently TypeScript playground links cannot be shared :( Edit2: Published on codesandbox.io, hopefully that works
Unfortunately there's no way to know which libraries have defined their types correctly, so you end up having to check the types you get back from every library you use.