When asserting that a field is definitely initialized in a class, what’s the difference between !
(exclamation point, definite assignment assertion) and the declare
modifier?
The following code is an error in strict mode since TS doesn’t know for sure that the field has been initialized.
class Person {
name: string; // Error: Property 'name' has no initializer and is not definitely assigned in the constructor.
}
I’ve seen 2 ways of handling this:
- Definite assignment assertion:
class Person { name!: string; }
- Ambient declaration:
class Person { declare name: string; }
I can’t see the difference between these two techniques. They both cure the error, they both don’t emit code, and they both don’t allow initializers. Does ambient declaration (released in v3.7) simply outdate definite assignment (released in v2.7)? Should declare
be used instead of !
whenever possible?
Declare is mainly useful for mocking values when playing around with the type system. In production code, it's rarely used.
This says to the compiler:
The
declare
keyword is typically used in type definition files that provide typings for files that Typescript cannot get type information from (such as plain JS files). So if I was reading your code, I would assume thatname
is getting monkey patched in from some JS file somewhere, and you are noting that here.I would be incorrect.
This says to the compiler:
Using this form it's clear to anyone reading the code that
name
is undefined at first, but is treated like a string anyway. That means it must be set in this file somewhere, just probably not in the constructor.From what you are saying, I would be correct in those assumptions.
In practice, in this particular case, the result is nearly identical. In both cases you have a string property that you never have to actually initialize. However, I would argue that the
name!: string
is far more clear about what is actually going on.Also,
declare
never emits code. It makes something only exist in the type system. (Thanks for mentioning this @NoelDeMartin)Compiles to:
Note that
baz
is completely absent from the output.Lastly though, I have to mention, you should probably just refactor your code so that you can assign the property in the constructor. Both those methods are not as type safe since you could potentially treat an uninitialized value as a
string
, which will likely cause a crash if it happens.