Javaddict
Javaddict

Reputation: 586

How to force function parameters to match key and type of object?

I would like to force the 2 parameters of a function to respect the name and the type of an object. So I am looking for the XXX type of the val parameter to be the type of the T[key]:

class I<T> {}

class W<T extends object> {
    field<K extends keyof T>(key: K, val: XXX) { void 0;}
}

In order to have the following behavior:


class A {
    i:number=3
    s:string="test"
}

let Winstance:W<A>=new W<A>()

Winstance.field("i",new I<number>()) // OK
Winstance.field("s",new I<number>()) // NOK
Winstance.field("i",new I<string>()) //NOK
Winstance.field("s",new I<string>()) //OK

Is there any way? I tryed

class W<T extends object> {
    field<K extends keyof T>(key: K, val: I<T[K]>) { void 0;}
}

But it doesn't work

Upvotes: 0

Views: 188

Answers (2)

Javaddict
Javaddict

Reputation: 586

Thank you jcaz, the problem was that I was an empty class. It is OK if I add a property (example):

class I<T> {
  x = (x: T) => x // <-- add a property that uses the type parameter
}

Upvotes: 0

Samathingamajig
Samathingamajig

Reputation: 13283

Make a generic and use that key K to have a more specific selector for val

class W<T extends object> {
    field<K extends keyof T>(key: K, val: T[K]) { void 0;}
}


class A {
  i:number=3
  s:string="test"
}

let Winstance:W<A>=new W<A>()

Winstance.field("i",45) // OK
Winstance.field("s",45) // NOK
Winstance.field("i","astring") //NOK
Winstance.field("s","astring") //OK

TS Playground

Upvotes: 1

Related Questions