What is a const cast in TypeScript?
Resources and links
Links from this session
These links apply generally
- YouTube channel
- Twitter account
- Why am I doing this?
- Subreddit for help and questions
- Github account for the stream code
- Topic suggestions
Terminal
Notes
const
casts are useful for telling the TypeScript compiler to infer the type of a value as something very specific, rather than something general. For example,
// note, `foo as const` is the same as `<const> foo` let x = 10 as const; // Type 10 let x2 = 10 ; // Type number let y = <const> [10, 20]; // Type readonly [10, 20] let y2 = [10, 20]; // Type number[] let z = { text: "hello" } as const; // Type { readonly text: "hello" } let z2 = { text: "hello" }; // Type { text: string }
Use it if you have to create large objects that you want to be immutable (unable to change).
// Without a const cast, you need to specify `readonly` or use // the convenient `Readonly` type Microsoft provides const bigImmutableObject = { readonly a: 1, readonly b: 2, readonly c: { readonly c1: 3, readonly c2: 4 } } // This seems nicer const bigImmutableObject = { a: 1, b: 2, c: { c1: 3, c2: 4 } } as const
Further Learning
Here are some things to try if you want to dive deeper.
// Create a function that utilizes the extra information // captured by the const cast. interface MyType { // Decide what should go here } function doStuff(myType: MyType) { // Do something with it } // Use it const myObject = { // should match MyType } as const doStuff(myObject) // should work
Topic Suggestions
Feel free to recommend or suggest a topic that you’re interested in or that you think would be useful. It can be anything, it doesn’t have to be related to what we’ve done so far.