DEV Community

ScottPony
ScottPony

Posted on

Mapped Object Types

映射

將一個集合中的每個元素與另一個元素關聯的動作。

TypeScript中的映射類型

允許你通過轉換現有類型的屬性來創建新的類型。

範例

type MoviesByGenre = {
  action: 'Die Hard';
  comedy: 'Groundhog Day';
  sciFi: 'Blade Runner';
  fantasy: 'The Lord of the Rings: The Fellowship of the Ring';
  drama: 'The Shawshank Redemption';
  horror: 'The Shining';
  romance: 'Titanic';
  animation: 'Toy Story';
  thriller: 'The Silence of the Lambs';
};
Enter fullscreen mode Exit fullscreen mode
//透過映射來定義新型別MovieInfoByGenre
type MovieInfoByGenre<T> = {
        //**in**專為映射所使用的運算子,告訴TypeScript,K為**in**運算子右邊集合內的單一元素
        //**keyof T**: T物件所有鍵(Property)的聯集
    [K in keyof T]: {
        name: string;
        year: number;
        director: string;
    };
};
Enter fullscreen mode Exit fullscreen mode
type Example = MovieInfoByGenre<MoviesByGenre>;

/*Example為: {
    action: {
        name: string;
        year: number;
        director: string;
    };
    comedy: {
        name: string;
        year: number;
        director: string;
    };
    sciFi: {
        name: string;
        year: number;
        director: string;
    };
    fantasy: {
        name: string;
        year: number;
        director: string;
    };
    drama: {
        name: string;
        year: number;
        director: string;
    };
    horror: {
        name: string;
        year: number;
        director: string;
    };
    romance: {
        name: string;
        year: number;
        director: string;
    };
    animation: {
        name: string;
        year: number;
        director: string;
    };
    thriller: {
        name: string;
        year: number;
        director: string;
    };
  }*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)