Home > Software design >  TypeScript function generic parameter whitch is composed not contains expected field
TypeScript function generic parameter whitch is composed not contains expected field

Time:03-19

How can I pass document composed like in example to function with generic parameter?

type WithId = {
    _id?: string;
};

type DocumentWithId<D> = D & WithId;

type Contact = {
    title: string;
};

type ContactWithId = DocumentWithId<Contact>;

function saveDocument<D extends DocumentWithId<any>>(document: D) {
    if (document._id) {
        console.log('Update', document);
    } else {
        console.log('Create', document);
    }
}

When I run this code, compile error occured:

Property '_id' does not exist on type 'D'.

Run example here

CodePudding user response:

Try this:

type DocumentWithId<any> = any & WithId; //Becomes any that's why it's not working

function saveDocument<D extends DocumentWithId<unknown>>(document: D) {
    if (document._id) {
        console.log('Update', document);
    } else {
        console.log('Create', document);
    }
}

CodePudding user response:

You're already passing the generic parameter to type DocumentWithId<D> = D & WithId;, so there's no need to specify the generic parameter of the function.

type WithId = {
    _id?: string;
};

type DocumentWithId<D> = D & WithId;

type Contact = {
    title: string;
};

type ContactWithId = DocumentWithId<Contact>;

function testId<D>(document: DocumentWithId<D>) {
    if (document._id) {
        console.log(`ID filled: ${document._id}`);
    }
}

Playground

  • Related