Bilow
Bilow

Reputation: 2314

Property does not exist on generic type T

I do not understand the error I am getting below

Here is a minimal reproducible example

type Left = {
    element: 0
}

type Right = {
    element: 1
}

interface Typings {
    "left": Left
    "right": Right
}

function foo<T extends keyof Typings>(obj: T) {
    console.log(obj.element)
                 // ^^^^^^^
                 // Property 'element' does not exist on type 'T'.
}

Of course I can still copy-paste my function

function fooLeft(obj: Left) {
    console.log(obj.element)
}

function fooRight(obj: Right) {
    console.log(obj.element)
}

It works perfectly, but it doesn't seem clean... How can I avoid copy-pasting my function?

I cannot use an union, in the actual code several parameters depend on Typings.

Upvotes: 0

Views: 368

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 186984

keyof Typings

This means the strings "left" | "right" which are the keys of Typings. You seem to want the types of the properties instead Left | Right.

To do that, you want T to be the union type of all of its properties. You do that by indexing the type by all of it's own keys.

function foo<T extends Typings[keyof Typings]>(obj: T) {
    console.log(obj.element) // obj is: Left | Right
}

Playground

Upvotes: 2

Related Questions