LoginSignup
0
0

TypeScriptでExcludeを利用する

Posted at

はじめに

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

ソースコード

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

// すべてのプロパティのキーをユニオン型として取得
type PersonKeys = keyof Person;

// 'name' を除外したキーのユニオン型を作成
type ExcludeName = Exclude<PersonKeys, 'name'>;

// ExcludeNameに該当するプロパティだけを持つ型を作成
type PersonWithoutName = Pick<Person, ExcludeName>;

const person: PersonWithoutName = {
  age: 30,
  address: '123 Main St',
  // name: 'John', // エラー, 'name' は 'PersonWithoutName' 型に存在しません
};

console.log(person); // { age: 30, address: '123 Main St' }

personはnameを除外されているので、値を渡すとその時点でエラーがおきます。

実行結果
~/develop/react/typescript_node$ ts-node index.ts 
{ age: 30, address: '123 Main St' }
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