LoginSignup
0
0

TypeScriptでPartialを利用する

Posted at

はじめに

TypeScriptで基本型に対し、すべてOptionalにするPartialを紹介します。

index.ts
// Person 型の定義
type Person = {
  name: string;
  age: number;
  address: string;
};

// PartialPerson 型の定義(Person のすべてのプロパティがオプショナル)
type PartialPerson = Partial<Person>;

// PartialPerson 型のオブジェクトの例
const person1: PartialPerson = {
  name: "Alice"
};

const person2: PartialPerson = {
  age: 30
};

const person3: PartialPerson = {
  address: "123 Main St"
};

const person4: PartialPerson = {};

// 各オブジェクトの内容をコンソールに出力
console.log(person1); // { name: 'Alice' }
console.log(person2); // { age: 30 }
console.log(person3); // { address: '123 Main St' }
console.log(person4); // {}

// このファイルは TypeScript (.ts) ファイルとして保存し、
// TypeScript コンパイラを使用して実行する必要があります。

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