简体   繁体   中英

Get property of generic type

In our angular6 project we activated the "noImplicitAny": true setting and found out that this gave some problems on retrieving a value from generic types.

At the moment we retrieve the value by current['orderBy'] , but this gives the following error: Element implicitly has an 'any' type because type '{}' has no index signature.

We can solve this by casting current to any (<any>current)['orderBy'] , but this is in our eyes worse coding.

We've tried to cast 'orderBy' current['orderBy' as keyof T] , but this not nice code and gives the retrieved property the wrong type ( :T[keyof T] ) which in this case makes it impossible to use in calculations (in this case it should be of type number)

We've also tried to make a function were you can pass the generic type and the name of the property we want to get the value of (found here https://blog.mariusschulz.com/2017/01/06/typescript-2-1-keyof-and-lookup-types ).

export const prop = <T, K extends keyof T>(obj: T, key: K) => { return obj[key]; };

which works if current was not a generic type, but it is so it gives the following error: Argument of type '"orderBy"' is not assignable to parameter of type 'keyof T' .

So does anyone know another way to retrieve the property value of a generic type that might work? (also in this case it is orderBy we tried to retrieve but it could be any other field of the generic type)

If you have an unconstrained type parameter, typescript will not let you access any properties of the type since it does not know such accesses are valid. Without noImplictAny this worked as you could access any property of any type.

With no implicit any, you will need to be more explicit about what properties your generic type has and what their possible types are:

class Foo<T extends { orderBy: string }> {
    m(current: T) {
        let o = current['orderBy']; // string
        let o2 = current.orderBy; // or just . notation
    }
}

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