3 ms·
> Ah but see, the compiler is a guard-rail. Yes, I agree. It's a guard-rail which is missing in scripting languages like JavaScript and Ruby, and which some pe
by Zarel 8y ago
> Ah but see, the compiler is a guard-rail.
Yes, I agree. It's a guard-rail which is missing in scripting languages like JavaScript and Ruby, and which some people are resisting adding.
> Example 1 can be statically verified by a JavaScript type checker. Example 2 can't.
With type assertions, it's not really limiting at all. For instance, I'd write example 2 as:
for (let i = 0; i < 3; i++) {
console.log(foo['bar' + i as keyof typeof foo]);
}
If you weren't as experienced with TypeScript, you can also just throw around `any` assertions until the problem goes away:
let foo: any = {
bar0: 12,
bar1: 14,
bar2: 16
};
Or if you wanted to be tricky, you could even just assert a specific key:
for (let i = 0; i < 3; i++) {
console.log(foo['bar' + i as 'bar0']);
}
It's true that there are a lot of things typecheckers can't check. But that's no reason to give up on the things they _can_ check.