TypeScript definite assignment assertions

TypeScript never stops improving, although most changes over the past year have been “non syntactical” – i.e. there have been a huge swathe of improvements to how types are handled, and a large slice of improvements to make the tooling even better. It has a been a while, though, since we got a new character to decorate our code. The wait is over, thanks to the TypeScript Definite Assignment Assertion. Let’s take a look at it with a short example.

Warning Triangle

No definite assignment

The new feature is related to the following improved compile-time check. In the example below, I forgot to assign a value to the wordsPerMinute property. This can happen when you forget to add a default value, or when you forget to initialize it in the constructor, or (as below) when you forget to map a parameter to the property (remember, you don’t need to manually map constructor parameters !).

Whatever the reason, if you compile using the strict flag (I keep telling you to use it), you’ll get the following error, known as a definite assignment error because there is no definite assignment:

app.ts(2,13): error TS2564: Property ‘wordsPerMinute’ has no initializer and is not definitely assigned in the constructor.

Fixing, and definite assignment assertions

The correct fix is probably to assign this.wordsPerMinute = wordsPerMinute in the constructor – but in some cases, you may be doing something funky where the dependency will be resolved in a way the compiler is unable to determine.

When you need to allow a property with no definite assignment, you can use the definite assignment assertion . This is a very grand name for adding a bang (!) to the property name.

This will only work in TypeScript 2.7 and newer.

On the whole, unless you have an iron-clad reason to use it – you’ll probably want to avoid the definite assignment assertion. In most cases, the real value of this feature lies in the part that detects unassigned properties.

Warning Triangle, Public Domain. Wikipedia .

Steve Fenton

Steve Fenton is a Principal DevEx Researcher at Octopus Deploy and seven-time Microsoft MVP for developer technologies. He's a Software Punk and writer.

Categories:

  • Programming

Three Ways to Improve Software Development

Testing NPM publish with a dry run

A drawer full of junk

Code organisation and junk

Was this page helpful?

Background Reading: Classes (MDN)

TypeScript offers full support for the class keyword introduced in ES2015.

As with other JavaScript language features, TypeScript adds type annotations and other syntax to allow you to express relationships between classes and other types.

Class Members

Here’s the most basic class - an empty one:

This class isn’t very useful yet, so let’s start adding some members.

A field declaration creates a public writeable property on a class:

As with other locations, the type annotation is optional, but will be an implicit any if not specified.

Fields can also have initializers ; these will run automatically when the class is instantiated:

Just like with const , let , and var , the initializer of a class property will be used to infer its type:

--strictPropertyInitialization

The strictPropertyInitialization setting controls whether class fields need to be initialized in the constructor.

Note that the field needs to be initialized in the constructor itself . TypeScript does not analyze methods you invoke from the constructor to detect initializations, because a derived class might override those methods and fail to initialize the members.

If you intend to definitely initialize a field through means other than the constructor (for example, maybe an external library is filling in part of your class for you), you can use the definite assignment assertion operator , ! :

Fields may be prefixed with the readonly modifier. This prevents assignments to the field outside of the constructor.

Constructors

Background Reading: Constructor (MDN)

Class constructors are very similar to functions. You can add parameters with type annotations, default values, and overloads:

There are just a few differences between class constructor signatures and function signatures:

  • Constructors can’t have type parameters - these belong on the outer class declaration, which we’ll learn about later
  • Constructors can’t have return type annotations - the class instance type is always what’s returned

Super Calls

Just as in JavaScript, if you have a base class, you’ll need to call super(); in your constructor body before using any this. members:

Forgetting to call super is an easy mistake to make in JavaScript, but TypeScript will tell you when it’s necessary.

Background Reading: Method definitions

A function property on a class is called a method . Methods can use all the same type annotations as functions and constructors:

Other than the standard type annotations, TypeScript doesn’t add anything else new to methods.

Note that inside a method body, it is still mandatory to access fields and other methods via this. . An unqualified name in a method body will always refer to something in the enclosing scope:

Getters / Setters

Classes can also have accessors :

Note that a field-backed get/set pair with no extra logic is very rarely useful in JavaScript. It’s fine to expose public fields if you don’t need to add additional logic during the get/set operations.

TypeScript has some special inference rules for accessors:

  • If get exists but no set , the property is automatically readonly
  • If the type of the setter parameter is not specified, it is inferred from the return type of the getter

Since TypeScript 4.3 , it is possible to have accessors with different types for getting and setting.

Index Signatures

Classes can declare index signatures; these work the same as Index Signatures for other object types :

Because the index signature type needs to also capture the types of methods, it’s not easy to usefully use these types. Generally it’s better to store indexed data in another place instead of on the class instance itself.

Class Heritage

Like other languages with object-oriented features, classes in JavaScript can inherit from base classes.

implements Clauses

You can use an implements clause to check that a class satisfies a particular interface . An error will be issued if a class fails to correctly implement it:

Classes may also implement multiple interfaces, e.g. class C implements A, B { .

It’s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesn’t change the type of the class or its methods at all . A common source of error is to assume that an implements clause will change the class type - it doesn’t!

In this example, we perhaps expected that s ’s type would be influenced by the name: string parameter of check . It is not - implements clauses don’t change how the class body is checked or its type inferred.

Similarly, implementing an interface with an optional property doesn’t create that property:

extends Clauses

Background Reading: extends keyword (MDN)

Classes may extend from a base class. A derived class has all the properties and methods of its base class, and can also define additional members.

Overriding Methods

Background Reading: super keyword (MDN)

A derived class can also override a base class field or property. You can use the super. syntax to access base class methods. Note that because JavaScript classes are a simple lookup object, there is no notion of a “super field”.

TypeScript enforces that a derived class is always a subtype of its base class.

For example, here’s a legal way to override a method:

It’s important that a derived class follow its base class contract. Remember that it’s very common (and always legal!) to refer to a derived class instance through a base class reference:

What if Derived didn’t follow Base ’s contract?

If we compiled this code despite the error, this sample would then crash:

Type-only Field Declarations

When target >= ES2022 or useDefineForClassFields is true , class fields are initialized after the parent class constructor completes, overwriting any value set by the parent class. This can be a problem when you only want to re-declare a more accurate type for an inherited field. To handle these cases, you can write declare to indicate to TypeScript that there should be no runtime effect for this field declaration.

Initialization Order

The order that JavaScript classes initialize can be surprising in some cases. Let’s consider this code:

What happened here?

The order of class initialization, as defined by JavaScript, is:

  • The base class fields are initialized
  • The base class constructor runs
  • The derived class fields are initialized
  • The derived class constructor runs

This means that the base class constructor saw its own value for name during its own constructor, because the derived class field initializations hadn’t run yet.

Inheriting Built-in Types

Note: If you don’t plan to inherit from built-in types like Array , Error , Map , etc. or your compilation target is explicitly set to ES6 / ES2015 or above, you may skip this section

In ES2015, constructors which return an object implicitly substitute the value of this for any callers of super(...) . It is necessary for generated constructor code to capture any potential return value of super(...) and replace it with this .

As a result, subclassing Error , Array , and others may no longer work as expected. This is due to the fact that constructor functions for Error , Array , and the like use ECMAScript 6’s new.target to adjust the prototype chain; however, there is no way to ensure a value for new.target when invoking a constructor in ECMAScript 5. Other downlevel compilers generally have the same limitation by default.

For a subclass like the following:

you may find that:

  • methods may be undefined on objects returned by constructing these subclasses, so calling sayHello will result in an error.
  • instanceof will be broken between instances of the subclass and their instances, so (new MsgError()) instanceof MsgError will return false .

As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.

However, any subclass of MsgError will have to manually set the prototype as well. For runtimes that don’t support Object.setPrototypeOf , you may instead be able to use __proto__ .

Unfortunately, these workarounds will not work on Internet Explorer 10 and prior . One can manually copy methods from the prototype onto the instance itself (i.e. MsgError.prototype onto this ), but the prototype chain itself cannot be fixed.

Member Visibility

You can use TypeScript to control whether certain methods or properties are visible to code outside the class.

The default visibility of class members is public . A public member can be accessed anywhere:

Because public is already the default visibility modifier, you don’t ever need to write it on a class member, but might choose to do so for style/readability reasons.

protected members are only visible to subclasses of the class they’re declared in.

Exposure of protected members

Derived classes need to follow their base class contracts, but may choose to expose a subtype of base class with more capabilities. This includes making protected members public :

Note that Derived was already able to freely read and write m , so this doesn’t meaningfully alter the “security” of this situation. The main thing to note here is that in the derived class, we need to be careful to repeat the protected modifier if this exposure isn’t intentional.

Cross-hierarchy protected access

TypeScript doesn’t allow accessing protected members of a sibling class in a class hierarchy:

This is because accessing x in Derived2 should only be legal from Derived2 ’s subclasses, and Derived1 isn’t one of them. Moreover, if accessing x through a Derived1 reference is illegal (which it certainly should be!), then accessing it through a base class reference should never improve the situation.

See also Why Can’t I Access A Protected Member From A Derived Class? which explains more of C#‘s reasoning on the same topic.

private is like protected , but doesn’t allow access to the member even from subclasses:

Because private members aren’t visible to derived classes, a derived class can’t increase their visibility:

Cross-instance private access

Different OOP languages disagree about whether different instances of the same class may access each others’ private members. While languages like Java, C#, C++, Swift, and PHP allow this, Ruby does not.

TypeScript does allow cross-instance private access:

Like other aspects of TypeScript’s type system, private and protected are only enforced during type checking .

This means that JavaScript runtime constructs like in or simple property lookup can still access a private or protected member:

private also allows access using bracket notation during type checking. This makes private -declared fields potentially easier to access for things like unit tests, with the drawback that these fields are soft private and don’t strictly enforce privacy.

Unlike TypeScripts’s private , JavaScript’s private fields ( # ) remain private after compilation and do not provide the previously mentioned escape hatches like bracket notation access, making them hard private .

When compiling to ES2021 or less, TypeScript will use WeakMaps in place of # .

If you need to protect values in your class from malicious actors, you should use mechanisms that offer hard runtime privacy, such as closures, WeakMaps, or private fields. Note that these added privacy checks during runtime could affect performance.

Static Members

Background Reading: Static Members (MDN)

Classes may have static members. These members aren’t associated with a particular instance of the class. They can be accessed through the class constructor object itself:

Static members can also use the same public , protected , and private visibility modifiers:

Static members are also inherited:

Special Static Names

It’s generally not safe/possible to overwrite properties from the Function prototype. Because classes are themselves functions that can be invoked with new , certain static names can’t be used. Function properties like name , length , and call aren’t valid to define as static members:

Why No Static Classes?

TypeScript (and JavaScript) don’t have a construct called static class the same way as, for example, C# does.

Those constructs only exist because those languages force all data and functions to be inside a class; because that restriction doesn’t exist in TypeScript, there’s no need for them. A class with only a single instance is typically just represented as a normal object in JavaScript/TypeScript.

For example, we don’t need a “static class” syntax in TypeScript because a regular object (or even top-level function) will do the job just as well:

static Blocks in Classes

Static blocks allow you to write a sequence of statements with their own scope that can access private fields within the containing class. This means that we can write initialization code with all the capabilities of writing statements, no leakage of variables, and full access to our class’s internals.

Generic Classes

Classes, much like interfaces, can be generic. When a generic class is instantiated with new , its type parameters are inferred the same way as in a function call:

Classes can use generic constraints and defaults the same way as interfaces.

Type Parameters in Static Members

This code isn’t legal, and it may not be obvious why:

Remember that types are always fully erased! At runtime, there’s only one Box.defaultValue property slot. This means that setting Box<string>.defaultValue (if that were possible) would also change Box<number>.defaultValue - not good. The static members of a generic class can never refer to the class’s type parameters.

this at Runtime in Classes

Background Reading: this keyword (MDN)

It’s important to remember that TypeScript doesn’t change the runtime behavior of JavaScript, and that JavaScript is somewhat famous for having some peculiar runtime behaviors.

JavaScript’s handling of this is indeed unusual:

Long story short, by default, the value of this inside a function depends on how the function was called . In this example, because the function was called through the obj reference, its value of this was obj rather than the class instance.

This is rarely what you want to happen! TypeScript provides some ways to mitigate or prevent this kind of error.

Arrow Functions

Background Reading: Arrow functions (MDN)

If you have a function that will often be called in a way that loses its this context, it can make sense to use an arrow function property instead of a method definition:

This has some trade-offs:

  • The this value is guaranteed to be correct at runtime, even for code not checked with TypeScript
  • This will use more memory, because each class instance will have its own copy of each function defined this way
  • You can’t use super.getName in a derived class, because there’s no entry in the prototype chain to fetch the base class method from

this parameters

In a method or function definition, an initial parameter named this has special meaning in TypeScript. These parameters are erased during compilation:

TypeScript checks that calling a function with a this parameter is done so with a correct context. Instead of using an arrow function, we can add a this parameter to method definitions to statically enforce that the method is called correctly:

This method makes the opposite trade-offs of the arrow function approach:

  • JavaScript callers might still use the class method incorrectly without realizing it
  • Only one function per class definition gets allocated, rather than one per class instance
  • Base method definitions can still be called via super .

In classes, a special type called this refers dynamically to the type of the current class. Let’s see how this is useful:

Here, TypeScript inferred the return type of set to be this , rather than Box . Now let’s make a subclass of Box :

You can also use this in a parameter type annotation:

This is different from writing other: Box — if you have a derived class, its sameAs method will now only accept other instances of that same derived class:

this -based type guards

You can use this is Type in the return position for methods in classes and interfaces. When mixed with a type narrowing (e.g. if statements) the type of the target object would be narrowed to the specified Type .

A common use-case for a this-based type guard is to allow for lazy validation of a particular field. For example, this case removes an undefined from the value held inside box when hasValue has been verified to be true:

Parameter Properties

TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public , private , protected , or readonly . The resulting field gets those modifier(s):

Class Expressions

Background Reading: Class expressions (MDN)

Class expressions are very similar to class declarations. The only real difference is that class expressions don’t need a name, though we can refer to them via whatever identifier they ended up bound to:

Constructor Signatures

JavaScript classes are instantiated with the new operator. Given the type of a class itself, the InstanceType utility type models this operation.

abstract Classes and Members

Classes, methods, and fields in TypeScript may be abstract .

An abstract method or abstract field is one that hasn’t had an implementation provided. These members must exist inside an abstract class , which cannot be directly instantiated.

The role of abstract classes is to serve as a base class for subclasses which do implement all the abstract members. When a class doesn’t have any abstract members, it is said to be concrete .

Let’s look at an example:

We can’t instantiate Base with new because it’s abstract. Instead, we need to make a derived class and implement the abstract members:

Notice that if we forget to implement the base class’s abstract members, we’ll get an error:

Abstract Construct Signatures

Sometimes you want to accept some class constructor function that produces an instance of a class which derives from some abstract class.

For example, you might want to write this code:

TypeScript is correctly telling you that you’re trying to instantiate an abstract class. After all, given the definition of greet , it’s perfectly legal to write this code, which would end up constructing an abstract class:

Instead, you want to write a function that accepts something with a construct signature:

Now TypeScript correctly tells you about which class constructor functions can be invoked - Derived can because it’s concrete, but Base cannot.

Relationships Between Classes

In most cases, classes in TypeScript are compared structurally, the same as other types.

For example, these two classes can be used in place of each other because they’re identical:

Similarly, subtype relationships between classes exist even if there’s no explicit inheritance:

This sounds straightforward, but there are a few cases that seem stranger than others.

Empty classes have no members. In a structural type system, a type with no members is generally a supertype of anything else. So if you write an empty class (don’t!), anything can be used in place of it:

How JavaScript handles communicating across file boundaries.

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Ryan Cavanaugh  (60)

Last updated: Nov 12, 2024  

DEV Community

DEV Community

RamaDevsign

Posted on Aug 17, 2022 • Originally published at blog.ramadevsign.com

What Does "!" Symbol Mean in Typescript?

In this short guide, I will introduce you to the Definite Assignment Assertion feature in typescript and demonstrate to you an interesting use case to implement this feature.

Prerequisites 

This guide assumes you have basic knowledge of Typescript , you have a basic understanding of the Stripe API , and you have installed the Typescript error translator extension.

The Problem

environment variables returns an error in typescript environment

The Solution

The solution in this case is to use the "!" symbol which is a feature in Typescript known as the definite assignment assertion. 

As defined in the official Typescript Documentation , the definite assignment assertion feature is used to tell the compiler that the variable assigned is indeed valid for all intents and purposes, even if Typescript's analyses cannot detect so. 

environment variables error fixed with ! symbol (definite assignment assertion)

With the definite assignment assertion, we can assert that indeed in this case we have environment variables ( process.env.STRIPE_SECRET_KEY ) in string format and there is nothing to worry about.

This workaround still leaves us with weaker type safety since any misconfiguration (in our case the environment variables) could lead to errors that cannot be caught at compile time. These errors can only be caught at runtime which beats the logic of having a strict and functional type checking system. With this in mind it's your responsibility to ensure correctness.

It's also good to note that previous Typescript versions used the "!" symbol as a non-null assertion operator. You can read more about this in the Typescript Documentation about Non-null assertion operator .

Thank you for reading this far and happy coding!

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

jaber-said profile image

The thing that strikes me the most is that you use like the colors I use in vs

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

thevediwho profile image

Custom Transitions in iOS 18 - #30DaysOfSwift

Vaibhav Dwivedi - Oct 21

blakeanderson profile image

Intelligent JSON Objects in Typescript Using class-transformer

Blake Anderson - Oct 21

grenishrai profile image

5 Projects That Can Get You Hired - 2024

Grenish rai - Nov 12

moh_moh701 profile image

C# Clean Code: Commenting Conventions

mohamed Tayel - Oct 22

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

IMAGES

  1. PPT

    what is definite assignment assertion

  2. PPT

    what is definite assignment assertion

  3. Using The "Definite Assignment Assertion" To Define Required Input

    what is definite assignment assertion

  4. Sentences with Assertion, Assertion in a Sentence in English, Sentences

    what is definite assignment assertion

  5. PPT

    what is definite assignment assertion

  6. TypeScript の definite assignment assertion operator の話

    what is definite assignment assertion

VIDEO

  1. Formulating Statement of Opinion and Assertion

  2. Assertion: Sine and cosine functions are periodic functions. Reason: Sinusoidal functions repeat

  3. How to solve Assertion and Reason Questions?

  4. Assertion and Reason for class 7 (Part 1)

  5. Assignment (law)

  6. Std-6 General English