4 ms·
Interesting. I swear that when I previously tried this approach I had to explicitly tell typescript that a string is indeed of a particular type: const test(
by azangru 7y ago
Interesting. I swear that when I previously tried this approach I had to explicitly tell typescript that a string is indeed of a particular type:
const test(direction: Direction) => direction;
test('up' as 'up');
But now that I'm testing in typescript playground, I no longer need to write the "as" part — simply `test('up');` works fine as well.
I wonder if you've seen this quirk of typescript before.
- skrebbel 7y agoI have. It's when you do const dir = "up"; // TS infers type "string" test(dir); // error For mutable variables (let/var), you usually want TS to infer `string` in the first line. IMO the fact that they also infer `string` for constants is a design flaw, that I hope will one day be fixed. They recently added a feature to make this less painful: const dir = "up" as const; test(dir); // works That's the same as `as "up"` bit without having to duplicate the string.
- mcaruso 7y ago`const` variables are actually inferred without widening. So in your example `dir` would be inferred as `"up"`, not `string`. If you use `let` (or `var`) however that would be true.
- azangru 7y agoMy god, you are right! (example in typescript playground: https://www.typescriptlang.org/play/#code/C4TwDgpgBAIglgJwgY2HA9gOygXigcgFcx8oAfAgE3QHdN8AoB0SKAFQgGdhcoBvBlCGVEKNFgBcsUagyYA3AwC+TBsizcowLjzwAKSgENghqR24BKXAD4oRkwDoRSWVkXrMm57yIkGAGwgeAFtCEwAjQPgEH2J8RWYdPT5nMTkpZyULRW1uZNTXTClQiKjELPkgA0 https://www.typescriptlang.org/play/#code/C4TwDgpgBAIglgJwgY...)
- skrebbel 7y agoOh wow! Great, thanks. I wonder how I recalled that wrong.