Typescript: Bug in docs

Created on 14 May 2019  Â·  4Comments  Â·  Source: microsoft/TypeScript

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html

// Type '"hello"'
let x = "hello" as const;

should have readonly in comment:

// Type readonly '"hello"'
let x = "hello" as const;

same applies to

// Type '"hello"'
let x = <const>"hello";
Working as Intended

Most helpful comment

They don’t, though. The main things as const does is: 1. Prevent literal types from being widened, and 2. Make object types have readonly properties. Primitive values like "hello" are only “read-only” as a consequence of assignability rules and static typing; let variables are still actually writable even with a const assertion:

let x = "hello" as const;
const c = "hello";
x = "goodbye" as any as "hello";  // okay
c =  "goodbye" as any as "hello";  // assignment to const, error!

All 4 comments

I don't think this is right - readonly is a modifier that applies to properties of types, not types themselves. So you can have { readonly x: "hello" } but not readonly "hello" (the latter is nonsensical as a literal is already read-only just by virtue of... being a literal).

This isn't a legal thing to write

image

I thought the comment was _explaining_ how variables infer readonly through the new type assertion feature.

They don’t, though. The main things as const does is: 1. Prevent literal types from being widened, and 2. Make object types have readonly properties. Primitive values like "hello" are only “read-only” as a consequence of assignability rules and static typing; let variables are still actually writable even with a const assertion:

let x = "hello" as const;
const c = "hello";
x = "goodbye" as any as "hello";  // okay
c =  "goodbye" as any as "hello";  // assignment to const, error!
Was this page helpful?
0 / 5 - 0 ratings

Related issues

bgrieder picture bgrieder  Â·  3Comments

seanzer picture seanzer  Â·  3Comments

manekinekko picture manekinekko  Â·  3Comments

weswigham picture weswigham  Â·  3Comments

Antony-Jones picture Antony-Jones  Â·  3Comments