4 ms·
Frankly it's a bit of a nuanced improvement, but I've seen it come up enough times that it's nice to have a real solution. The big value in `as const` is that `
by alangpierce 8y ago
Frankly it's a bit of a nuanced improvement, but I've seen it come up enough times that it's nice to have a real solution. The big value in `as const` is that `'ON' as const` has type `'ON'`, while `'ON'` has type `string`. If you have a function with a parameter of type `'OFF' | 'ON'` (a union type of two literal types), then it won't accept `string`, so you can end up in situations where the string `'ON'` won't fit because it was inferred as `string` in an intermediate step.
Here's a concrete example. The `printSwitch` call fails because `state: 'OFF'` is inferred as having a `string` value. In TS 3.4, you could write `'OFF' as const` and it would work.
https://www.typescriptlang.org/play/index.html#src=interface%20Switch%20%7B%0A%20%20%20%20state%3A%20'OFF'%20%7C%20'ON'%2C%0A%7D%0A%0Afunction%20printSwitch(s%3A%20Switch)%20%7B%0A%20%20%20%20console.log(s.state)%3B%0A%7D%0A%0Aconst%20s%20%3D%20%7B%0A%20%20%20%20state%3A%20'OFF'%2C%0A%7D%0A%0AprintSwitch(s)%3B%0A https://www.typescriptlang.org/play/index.html#src=interface...
TS is already pretty good about this, e.g. if you write `const s: Switch = {`, then it'll have enough context clues to know that `'OFF'` should have type `'OFF'`, but the new `as const` syntax is a way to explicitly say that the type shouldn't be expanded to `string`.