Skip to main content

[TS] TypeScript Utility Types

此篇為各筆記之整理,非原創內容,資料來源可見下方連結與文後參考資料。

  • Partial:把所有物件中屬性的型別都變成 optional
  • Pick:從物件中挑出特定屬性及其型別
  • Extract:只要取出,從許多項目中挑出能夠符合(extends)特定規則的
  • Exclude:排除後留下,從許多項目中排除符合(extends)特定規則的
  • Record:有特定的 key 和相同型別的值
/**
* Extract
**/
type OnlyString = Extract<'a' | 'b' | 1 | 2, string>; // "a" | "b"
/**
* Exclude
*/
enum PlaceType {
PARK = 'park',
ZOO = 'zoo',
OFFICE = 'office',
}
type WillGo = Exclude<PlaceType, PlaceType.OFFICE>; // type WillGo = Place.PARK | Place.ZOO
/**
* Record
*/
interface PlaceInfo {
address: string;
phone: string;
}
type PlaceRecord = Record<PlaceType, PlaceInfo>;
let placeRecord: PlaceRecord = {
[PlaceType.PARK]: {
address: 'foo',
phone: 'bar',
},
[PlaceType.ZOO]: {
address: 'foo',
phone: 'bar',
},
[PlaceType.OFFICE]: {
address: 'foo',
phone: 'bar',
},
};
Last updated on