Reputation: 2344
I see myself writing the following everywhere:
product: Product & { id: string; };
How do I write an interface, so that instead I can write
product: WithId<Product>;
I tried something like this, but the compiler doesn't like extending from generics:
export interface WithId<T> extends T {
id: string;
}
Upvotes: 2
Views: 46
Reputation: 20162
You can abstract the construct by abstraction of & {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] }
is nothing different like T
itself, so redundant.
Upvotes: 2
Reputation: 37604
You can use a type intersection
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
Upvotes: 0