0
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 1 year has passed since last update.

【TypeScript】{} で初期化したいけど,後からプロパティに値が入る可能性があるとき

Posted at

TypeScript で,{} で初期化したいけど後からプロパティに値が入る可能性がある場合,型アサーションを使って{} as 型 のように書けばよいらしいです.とても基本的なことだと思うのですが,自分の勉強のためにまとめておきます.

以下コード例です.

type Foo = {
    bar: string;
    hoge: string;
};

let foo = {} as Foo;
foo.bar = "Bar";

ちなみにこれは,以前私が書いた【TypeScript】Unknown型を絞り込みたい! で登場した Record でも書けることに気づきました.でも,わざわざこれで書きたいケースはほぼないと思います.

type Foo = {
    bar: string;
    hoge: string;
};

let foo = {} as Record<keyof Foo, string>;
foo.bar = "Bar";
0
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
0
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?