DEV Community

ScottPony
ScottPony

Posted on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay