File tree Expand file tree Collapse file tree 1 file changed +5
-5
lines changed Expand file tree Collapse file tree 1 file changed +5
-5
lines changed Original file line number Diff line number Diff line change @@ -53,15 +53,15 @@ class Foo {
5353declare let _foo: Foo ;
5454
5555// Same as before
56- let bar: typeof _foo .foo ;
56+ let bar: typeof _foo .foo ; // `bar` has type `number`
5757```
5858
5959## Capturing the type of magic strings
6060
6161Lots of JavaScript libraries and frameworks work off of raw JavaScript strings. You can use ` const ` variables to capture their type e.g.
6262
6363``` ts
64- // Capture both the *type* and *value* of magic string:
64+ // Capture both the *type* _and_ *value* of magic string:
6565const foo = " Hello World" ;
6666
6767// Use the captured type:
@@ -80,15 +80,15 @@ The `keyof` operator lets you capture the key names of a type. E.g. you can use
8080
8181``` ts
8282const colors = {
83- red: ' red ' ,
84- blue: ' blue '
83+ red: ' reddish ' ,
84+ blue: ' bluish '
8585}
8686type Colors = keyof typeof colors ;
8787
8888let color: Colors ; // same as let color: "red" | "blue"
8989color = ' red' ; // okay
9090color = ' blue' ; // okay
91- color = ' anythingElse' ; // Error
91+ color = ' anythingElse' ; // Error: Type '"anythingElse"' is not assignable to type '"red" | "blue"'
9292```
9393
9494This allows you to have stuff like string enums + constants quite easily, as you just saw in the above example.
You can’t perform that action at this time.
0 commit comments