If I have this:
class A {
a: string
}
Then TypeScript will tell me that Property 'a' has no initializer and is not definitely assigned in the constructor.
Quoting the key mutes the error:
class A {
'a': string
}
In my understanding there is no difference between quoting and not. So why is it the case?
This behavior is intentional. According to microsoft/TypeScript#20075, the pull request that implemented the --strictPropertyInitialization
compiler option:
Strict property initialization checks only apply to properties that are declared with proper identifiers. It does not apply to properties with computed names or properties with names specified as string or numeric literals.
// Compile with --strict class Test { a: number; // Error, not initialized "hello world": number; // No check }
In the type {a: string}
or the value {a: ""}
, the a
is an identifier, whereas in the type {"a": string}
or the value {"a": ""}
, the "a"
is a string literal. So the former receives checking while the latter does not.
Why this is intended isn't as clear. There are a few places in the language where bracket access (like computed properties) or string literals are exempted from checks as a way to allow developers to circumvent them, but obviously not everyone agrees with such decisions.