2 ms·
OK, the example with the "hello" literal string they have is quite bad then.
by coldtea 8y ago
OK, the example with the "hello" literal string they have is quite bad then.
- karanlyons 8y ago`as const` is useful there as well, as TypeScript’s type inference only narrows as far as the type and not the literal value. `let z = {text: "hello"}` has the shape `{text: string}`, with `as const` it has the shape `{text: "hello"}`.
- coldtea 8y agoYeah, but shouldn't it use: const z = 'hello' and then get the shape {text: 'hello'} automatically? Why use "let" along with "as const" instead of mere "const x = 'hello'" for that?
- karanlyons 8y agoBecause `const` is a js level keyword that has different semantics: it applies only to the reference binding being immutable, not the value as being so. `const a = "hello"` does have the shape `"hello"` as you’d expect, since strings are immutable in js and the `const` keyword makes the binding immutable as well. But objects are mutable, so TS can’t be a superset of javascript and change the semantics of that behavior. Hence `as const`. This is different to the widening of value types within objects, which is a tradeoff made towards unsoundness with the belief that it would otherwise make interoperability with existing js too difficult, for which `as const` now serves as a way to explicitly opt into sounder behavior.