Typescript: take a type and return a union type in a generic interface -


imagine simple collectionstore has methods creating , updating record. create() accepts set of attributes , returns same set id property added. update accepts set of same structure requires id property defined.

how express in typescript create() function accepts type t , returns t & {id: string} ?

i expect pattern expressed that:

interface collectionstore<t> {     updaterecord(t & {id: string}): void;     createrecord(t): t & {id: string}; } 

however code above isn't valid. please =)

you're right in how use union type, failed provide names functions params why error, should be:

interface collectionstore<t> {     updaterecord(record: t & { id: string }): void;     createrecord(record: t): t & { id: string }; } 

and then:

interface myrecord {     key: string; }  let a: collectionstore<myrecord> = ...;  a.updaterecord({ key: "key", id: "id" }); a.createrecord({ key: "key" }); 

(code in playground)

another option have have base interface records in id property optional:

interface record {     id?: string; }  interface collectionstore<t extends record> {     updaterecord(record: t): void;     createrecord(record: t): t; } 

but lose ability enforce updaterecord returns object id.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -