Expressingx
Expressingx

Reputation: 1572

Find object property by type

I have interface like

interface A {
   a: string;
}

interface B {
   b: string;
}

export interface C {
   rnd: A;
   rnd2: B;
}

And I want to have function like update<T>(setting: T) which finds the property of type T in the object, which implements interface C and update the property found (if exists already) values with setting passed.

Is there a way to achieve that ? I've tried with iterating and typeof but the compiler returns This condition will always return 'false' since types 'T' and 'string' has no overlap

Upvotes: 1

Views: 75

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250336

One posible solution is to pass in the key name. You can have the compiler check that the key name is a valid key of C and that the value parameter is of the same type as the specified key in C:

interface A { a: string; }

interface B { b: string; }

export interface C { rnd: A; rnd2: B;}

let allSettings: C = {} as C
function update<K extends keyof C>(key: K, setting: C[K]) {
    allSettings[key]  = setting;
}

update("rnd", { a: "" }) // ok
update("rnd", { b: "" }) // err
update("rnd3", { b: "" }) // err 

Upvotes: 1

Related Questions