const Assertions

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional TypeScript Masterclass Lessons

1.Introduction
free
⏱️ 1:54
2.Setup
free
⏱️ 5:44
3.Primitive Types
free
⏱️ 1:42
4.Instance Types
free
⏱️ 1:52
5.Arrays And Tuples
free
⏱️ 1:38
6.Objects
free
⏱️ 1:33
7.const declarations
free
⏱️ 1:03
8.Function Types
free
⏱️ 1:57
9.Structural Typing
free
⏱️ 2:10
10.Classes in TypeScript
free
⏱️ 1:48
11.Target Compiler Option
free
⏱️ 2:37
12.Generics
⏱️ 3:02
13.Special Types any And unknown
⏱️ 2:00
14.JavaScript to TypeScript
⏱️ 1:32
15.Frontend Projects
⏱️ 3:49
16.Type Assertions
⏱️ 2:15
17.Type Casting
⏱️ 1:16
18.Modules
⏱️ 1:55
19.Type Declarations
⏱️ 4:25
20.Creating NPM packages
⏱️ 3:20
21.Async Await
⏱️ 3:05
22.Running in NodeJS
⏱️ 1:40
23.Lexical this
⏱️ 2:34
24.readonly Modifier
⏱️ 1:59
25.Union Types
⏱️ 2:57
26.Literal Types
⏱️ 2:58
27.Type Narrowing
⏱️ 4:19
28.Discriminated Unions
⏱️ 3:29
29.Class Parameter Properties
⏱️ 1:02
30.Strict Compiler Option
⏱️ 6:18
31.null vs undefined
⏱️ 4:19
32.Intersection Types
⏱️ 2:03
33.Optional Modifier
⏱️ 2:47
34.Non Null Assertion Operator
⏱️ 3:40
35.Interfaces
⏱️ 2:28
36.Interface Declaration Merging
⏱️ 1:01
37.Types vs Interfaces
⏱️ 2:16
38.never Type
⏱️ 3:00
39.implements Keyword
⏱️ 1:25
40.Definite Assignment Assertion
⏱️ 2:31
41.User Defined Type Guards
⏱️ 2:02
42.Assertion Functions
⏱️ 3:42
43.Function Overloading
⏱️ 4:15
44.Call Signatures
⏱️ 2:53
45.Abstract Classes
⏱️ 1:53
46.Index Signatures
⏱️ 3:08
47.Readonly Arrays and Tuples
⏱️ 2:58
48.Double Assertions
⏱️ 2:20
49.const Assertions
⏱️ 3:55
50.this Parameter
⏱️ 2:33
51.Generic Constraints
⏱️ 2:43
52.typeof Type Operator
⏱️ 2:12
53.Lookup Types
⏱️ 3:12
54.keyof Type Operator
⏱️ 3:55
55.Conditional Types
⏱️ 4:39
56.Contitional Types with Unions and never
⏱️ 3:32
57.infer Keyword and `ReturnType<T>`
⏱️ 3:47
58.Mapped Types
⏱️ 2:48
59.Mapped Type Modifiers
⏱️ 3:37
60.Template Literal Type
⏱️ 4:28
61.Partial<T>
⏱️ 1:27
62.Required<T>
⏱️ 1:36
63.Readonly<T>
⏱️ 1:34
64.Record<K, T>
⏱️ 4:05
65.Project References
⏱️ 4:18
66.undefined vs. optional
⏱️ 2:48
67.satisfies Operator
⏱️ 2:42
68.PropertyKey Type
⏱️ 0:57
69.ThisType<T>
⏱️ 4:11
70.Awaited<T>
⏱️ 4:12
71.String Manipulation Types
⏱️ 3:36
72.Mapped Types as Clauses
⏱️ 4:01
73.Union vs Intersection Mental Model
⏱️ 3:36
74.Enums are Bad
⏱️ 8:11

const Assertions

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Default Type Inference

By default TypeScript type inference is armed for convenience. For example it infers the values as string and properties as mutable in the following example:

const dave = {
name: 'dave',
role: 'drummer',
skills: ['drumming', 'headbanging'],
};

// Allowed
dave.name = 'grohl';
dave.role = 'singer';
dave.skills.unshift('singing');

Narrowing the Inference

Using a const assertion as const helps TypeScript narrow the inferred type as much as possible (as const as possible). e.g.

const dave = {
name: 'dave',
role: 'drummer',
skills: ['drumming', 'headbanging'],
} as const;

dave.name = 'grohl'; // Error: readonly property
dave.role = 'singer'; // Error: readonly property
dave.skills.unshift('singing'); // Error: readonly array

Example Use Case

Its common to use as const when a library expects a particular literal value e.g. without using a const assertion:

function layout(settings: {
align: 'left' | 'center' | 'right',
padding: number,
}) {
console.log('Performing layout:', settings);
}

const example = {
align: 'left',
padding: 0,
};

layout(example); // Error: string not assignable to `'left' | 'center' | 'right'`

With a const assertion:

function layout(settings: {
align: 'left' | 'center' | 'right',
padding: number,
}) {
console.log('Performing layout:', settings);
}

const example = {
align: 'left' as const,
padding: 0,
};

layout(example); // Allowed
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Here we have a const variable called King that is storing the string Elvis. Now we know that const in JavaScript ensures that we cannot assign a different value to the king variable. An additional fact about JavaScript is that strings are immutable. That is none of the methods on the string primitive type allow you to mutate the string value. TypeScript understands this fact and automatically infers the type of the king variable to be the literal Elvis. However, objects and arrays in JavaScript are not immutable. Here we have an objective with two members name

00:34

and role of type string and a member skills of type array. Declaring the variable as a cons ensures that we cannot assign a different value to the day variable. However, the object itself is still mutable. So we can assign different values to the different members. For example, dave.name or Dave dot role, and even modify arrays by its methods. For example, Dave do skills unshift once more. TypeScript understands this fact and automatically infers the name and rules to be of type string so you can assign any string to them and the skills member to be a string array.

01:09

Now, of course, from what we know before, we can create a type specific to the Dave variable where we have these members, but they're all marked as read only. However, there is another way you can achieve this effect without creating a type specific to this variable. And that is using a cons assertion. Cons, assertions can be used on any value using as const cons. Assertions are essentially hints to the type inference that you wanted to infer the most immutable type possible. A consertion does three things. It converts any primitives to the literal types, any members

01:44

of an object to read only members and any arrays to read only couples. And now any mutations to the object will be highlighted as an error by type script in addition to providing immutability for objects. Cons, assertions are also commonly required when you are working with objects that have literal members. Let's look at an example. Here. We have a function called layout that expects an object with two members, a member aligned, which is restricted to a limited set of literal types and a member padding of type number. We create an example variable of such an object

02:18

and then we invoke the layout function with this example. And even though the example variable follows the required structure, we get an error from TypeScript. If you hover over the error message, you can see that TypeScript is complaining that string does not conform to the literal types that are required by the aligned member. The reason for this error is that for the object example, TypeScript has inferred the aligned member to be of type string. This is consistent with what we saw in our previous Dave's sample. We could fix it with an explicit type annotation for the example variable, or as we saw

02:51

before, use a constant assertion with this assertion in place. The align member is inferred to be the literal type left And the error goes away. Notice that all the members of the object have become read only and pairing is also inferred to be the literal type zero. As mentioned before, the cons assert can be applied on any value and we can be more specific where we want to apply. The cons assertion. Since we only need the aligned member to be inferred as the literal type and we don't want to change the other members to the literal types or read only properties, we can apply the assertion just to the left string

03:26

and now only the aligned member is inferred to be the literal left and all other members remain untouched. So when you are using a cons assertion to fix an error, it is always recommended that you apply it at the most specific point possible. Now, unlike other assertions, which essentially silence unsafe code cons, assertions are just hints that increased type safety by limiting the mutability so you can use them without worrying about your type checking becoming unsafe.

Professional TypeScript Masterclass

Professional TypeScript Masterclass

1.Introduction
free
⏱️ 1:54
2.Setup
free
⏱️ 5:44
3.Primitive Types
free
⏱️ 1:42
4.Instance Types
free
⏱️ 1:52
5.Arrays And Tuples
free
⏱️ 1:38
6.Objects
free
⏱️ 1:33
7.const declarations
free
⏱️ 1:03
8.Function Types
free
⏱️ 1:57
9.Structural Typing
free
⏱️ 2:10
10.Classes in TypeScript
free
⏱️ 1:48
11.Target Compiler Option
free
⏱️ 2:37
12.Generics
⏱️ 3:02
13.Special Types any And unknown
⏱️ 2:00
14.JavaScript to TypeScript
⏱️ 1:32
15.Frontend Projects
⏱️ 3:49
16.Type Assertions
⏱️ 2:15
17.Type Casting
⏱️ 1:16
18.Modules
⏱️ 1:55
19.Type Declarations
⏱️ 4:25
20.Creating NPM packages
⏱️ 3:20
21.Async Await
⏱️ 3:05
22.Running in NodeJS
⏱️ 1:40
23.Lexical this
⏱️ 2:34
24.readonly Modifier
⏱️ 1:59
25.Union Types
⏱️ 2:57
26.Literal Types
⏱️ 2:58
27.Type Narrowing
⏱️ 4:19
28.Discriminated Unions
⏱️ 3:29
29.Class Parameter Properties
⏱️ 1:02
30.Strict Compiler Option
⏱️ 6:18
31.null vs undefined
⏱️ 4:19
32.Intersection Types
⏱️ 2:03
33.Optional Modifier
⏱️ 2:47
34.Non Null Assertion Operator
⏱️ 3:40
35.Interfaces
⏱️ 2:28
36.Interface Declaration Merging
⏱️ 1:01
37.Types vs Interfaces
⏱️ 2:16
38.never Type
⏱️ 3:00
39.implements Keyword
⏱️ 1:25
40.Definite Assignment Assertion
⏱️ 2:31
41.User Defined Type Guards
⏱️ 2:02
42.Assertion Functions
⏱️ 3:42
43.Function Overloading
⏱️ 4:15
44.Call Signatures
⏱️ 2:53
45.Abstract Classes
⏱️ 1:53
46.Index Signatures
⏱️ 3:08
47.Readonly Arrays and Tuples
⏱️ 2:58
48.Double Assertions
⏱️ 2:20
49.const Assertions
⏱️ 3:55
50.this Parameter
⏱️ 2:33
51.Generic Constraints
⏱️ 2:43
52.typeof Type Operator
⏱️ 2:12
53.Lookup Types
⏱️ 3:12
54.keyof Type Operator
⏱️ 3:55
55.Conditional Types
⏱️ 4:39
56.Contitional Types with Unions and never
⏱️ 3:32
57.infer Keyword and `ReturnType<T>`
⏱️ 3:47
58.Mapped Types
⏱️ 2:48
59.Mapped Type Modifiers
⏱️ 3:37
60.Template Literal Type
⏱️ 4:28
61.Partial<T>
⏱️ 1:27
62.Required<T>
⏱️ 1:36
63.Readonly<T>
⏱️ 1:34
64.Record<K, T>
⏱️ 4:05
65.Project References
⏱️ 4:18
66.undefined vs. optional
⏱️ 2:48
67.satisfies Operator
⏱️ 2:42
68.PropertyKey Type
⏱️ 0:57
69.ThisType<T>
⏱️ 4:11
70.Awaited<T>
⏱️ 4:12
71.String Manipulation Types
⏱️ 3:36
72.Mapped Types as Clauses
⏱️ 4:01
73.Union vs Intersection Mental Model
⏱️ 3:36
74.Enums are Bad
⏱️ 8:11