首页 > 解决方案 > 将 intersect 类型封装到接口中

问题描述

我看到自己到处都在写以下内容:

product: Product & { id: string; };

如何编写接口,以便我可以编写

product: WithId<Product>;

我试过这样的东西,但编译器不喜欢从泛型扩展:

export interface WithId<T> extends T {
    id: string;
}

标签: typescript

解决方案


您可以通过抽象来抽象构造& {id: string}

export type WithId<T> = T & { id: string }

type Example = WithId<{ a: number }> // {a: number, id: string}
const example: Example = {a: 1, id: 'id'}

PS。{ [K in keyof T]: T[keyof T] }和它本身没什么不同T,所以多余。


推荐阅读