网站搜索

typescript - 将交叉类型封装到接口中


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

product: Product & { id: string; };

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

product: WithId<Product>;

我尝试了类似的东西,但编译器不喜欢从泛型继承:

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

答案#1

你可以通过抽象 & {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'}

附注:{ [K in keyof T]: T[keyof T] } 和 T 本身没有什么不同,所以是多余的。

答案#2

你可以使用类型交叉

export type WithId<T> = { [K in keyof T]: T[keyof T] } & { id: string }


interface product { myNew: string }
let et: WithId<product> = { myNew: "s", id: "s" } // ok
let et: WithId<product> = { test: "s", id: "s" } // error