简体   繁体   中英

Typescript generics: How to define properties

I'm struggling a bit with generics in typescript and just encountered the following

save<T>(data: T): Observable<T> { 
    const created = data.createdTime;
    ...
}

The problem here is that typescript tells me that createdTime is an unknown property. However, in my case, any data object passed to save will have a createdTime property. What is the correct way to tell typescript that data has this property ?

Make T extend an interface

interface Data {
    createdTime: number
}

save<T extends Data>(data: T): Observable<T> { 
    const created = data.createdTime;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM