简体   繁体   English

打字稿泛型:如何定义属性

[英]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. 这里的问题是打字稿告诉我createdTime是未知属性。 However, in my case, any data object passed to save will have a createdTime property. 但是,就我而言,传递给save任何data对象都将具有createdTime属性。 What is the correct way to tell typescript that data has this property ? 告诉打字稿data具有此属性的正确方法是什么?

Make T extend an interface 使T扩展接口

interface Data {
    createdTime: number
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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