3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScript の strictPropertyInitialization を有効にしたいが、怒られる時

Posted at

Node.js + TypeScript で開発しており、何らかの ORM を使っている時に、なった。

こういう時

class User {
  email: string
}

下記のエラーが出る

Property 'name' has no initializer and is not definitely assigned in the constructor. 

下記のように、単純に ?undefined を許可すると

class User {
  email?: string
}

下記のコードが通ってしまう

new User({ email: undefined })

これを避けるには、 assertion modifier (!) を付けてあげれば良い

class User {
  email!: string
}

この状態で下記のコードを書くと

new User({ email: undefined })

いい感じに怒られる。

Type 'undefined' is not assignable to type 'string'.

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?