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?

More than 3 years have passed since last update.

[TypeScript] オブジェクト型でプロパティを増やしたり減らしたりする

Last updated at Posted at 2021-10-25

ある型定義からプロパティを増やしたい場合

他にもあるような気がするけど、とりあえずいくつかのパターン。

type type1_1 = {
  a: string
  b: string
}

const obj1_1: type1_1 = {
  a: 'A',
  b: 'B',
  // c: 'C',  // ERROR
}
console.log(obj1_1);  // { a: "A", b: "B" }

const obj1_2: type1_1 & { c: string } = {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj1_2);  // { a: "A", b: "B", c: "C" }

type type1_2 = type1_1 & { c: string }
const obj1_3: type1_2 = {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj1_3);  // { a: "A", b: "B", c: "C" }

type type2 = {
  a: string
  b: string
  c?: string
}
const obj2_1: type2 = {
  a: 'A',
  b: 'B',
}
console.log(obj2_1);  // { a: "A", b: "B" }

const obj2_2: type2= {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj2_2);  // { a: "A", b: "B", c: "C" }

type type3_1 = {
  a: string
  b: string
}
type type3_2 = {
  a: string
  b: string
  c: string
}
const obj3_1: type3_1 | type3_2 = {
  a: 'A',
  b: 'B',
}
console.log(obj3_1);  // { a: "A", b: "B" }

const obj3_2: type3_1 | type3_2= {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj3_2);  // { a: "A", b: "B", c: "C" }

type type3_3 = type3_1 | type3_2
const obj3_3: type3_3 = {
  a: 'A',
  b: 'B',
}
console.log(obj3_3);  // { a: "A", b: "B" }

const obj3_4: type3_3 = {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj3_4);  // { a: "A", b: "B", c: "C" }

// let obj3_5: type3_3; // ERROR if (obj3_5.c の部分がうまく動かない
let obj3_5: any
obj3_5 = obj3_3
if (obj3_5.c === undefined) {
  obj3_5.c = 'C1'
}
console.log(obj3_5);  // { a: "A", b: "B", c: "C1" }

obj3_5 = obj3_4
if (obj3_5.c === undefined) {
  obj3_5.c = 'C2'
}
console.log(obj3_5);  // { a: "A", b: "B", c: "C" }

anyなしにしようとするとなかなか難しいところ。

ある型定義からプロパティを消したい場合

こんな風に実装する

interface type1_1 {
  a: string
  b: string
  c: string
}

const obj1_1: type1_1 = {
  a: 'A',
  b: 'B',
  c: 'C',
}
console.log(obj1_1);  // { a: "A", b: "B", c: "C" }

type type2_1 = Pick<type1_1, "a" | "b">

const obj2_1: type2_1 = {
  a: 'A',
  b: 'B',
  // c: 'C',  // ERROR
}
console.log(obj2_1);  // { a: "A", b: "B" }

type type2_2 = Omit<type1_1, "a" | "b">

const obj2_2: type2_2 = {
  // a: 'A',  // ERROR
  // b: 'B',  // ERROR
  c: 'C',
}
console.log(obj2_2);  // { c: "C" }

参考

TypeScript特有の組み込み型関数 || log.pocka.io
https://log.pocka.io/ja/posts/typescript-builtin-type-functions/

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?