0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonエンジニアのTypeScript勉強記録 part2 オブジェクトとオブジェクトの型

0
Posted at

オブジェクトの基本

Pythonでいうところの辞書(dictionary)
プロパティ名には文字式も使用可能

const obj = {
  foo: 123,
  "bar": "Hello, world!"
};

console.log(obj.foo)
console.log(obj.bar) // 文字式でも指定方法は同じ

スプレッド構文

...式という形の構文
オブジェクト作成時にプロパティを別のオブジェクトからコピーしてくるのに使う

const obj1 = {
  foo: 123,
  bar: 456
};

const obj2 = {
  baz: 789,
  ...obj1
};

// obj2は{foo: 123, bar: 456, baz: 789}

オブジェクトの型

type文でオブジェクトの型をつくる

type FooBarObj = {
  foo: number,
  bar: string
};
const obj: FooBarObj = {
  foo: 123,
  "bar": "Hello, world!"
};

オブジェクトの中身を先に定義してからtype文を書くこともできる

const obj: FooBarObj = {
  foo: 123,
  "bar": "Hello, world!"
};
type FooBarObj = {
  foo: number,
  bar: string
};

おわりに

  • "型"に関する項目はこれまで触れてこなかったことが多いため理解に時間がかかる
  • 書籍には色々な構文が紹介されているが、どこまで実務でよく使うものなのか判断がつかない
  • 細かいところは流し読みで、必要になったときに戻って読む、辞書のような使い方がよさそう
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?