# TypeScriptで定義済みの型からプロパティを取り出し新しい型を作る方法

2 min read
Table of Contents

過去に定義した型から新しい型を生成する

TypeScriptで型を定義したのち、その中の一部を使いたくなる時がある。

例えば、Personという型を定義した時、

export interface Person {
age: number
sex: 'man' | 'woman'
bloodType: 'A' | 'B' | 'O' | 'AB'
}

bloodTypeという型を使用したいという時がある。

そういう時は、

export type BloodType = Person['bloodType']

上記のように書くことで型を取り出すことができる。

最初から最小で作るの吉?

export interface Age {
age: number;
}
export type Sex = 'man' | 'woman';
export type BloodType = 'A' | 'B' | 'O' | 'AB';
export interface Person {
age: Age;
sex: Sex;
bloodType: BloodType;
}

そもそも上記のように最小で作っておいた方がいい?

ただ使わないものも多いので、取り出す方が労力が少なく済みそうな気がする。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments