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?

TypeScriptでOmitを利用する。

Posted at

はじめに

TypeScriptで基本型に対し、一部の型を除外するOmitを紹介します。

ソースコード

omit.ts
type Person = {
    name: string;
    age: number;
    address: string;
  };

  type PersonWithoutAddress = Omit<Person, 'address'>;

  const person: PersonWithoutAddress = {
    name: 'Alice',
    age: 30,
    // 'address' プロパティは省略されているので指定不可
    // address: '123 Main St',
  };

console.log(person); // { name: 'Alice', age: 30 }

Omitとは日本語で「省く」という意味です。任意の型から一部のプロパティを省いて新規の型を作成します。

実行結果

実行結果
~/develop/react/typescript_node$ ts-node omit.ts 
{ name: 'Alice', age: 30 }
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?