按类型查找对象属性

问题描述 投票:1回答:1

我有界面喜欢

interface A {
   a: string;
}

interface B {
   b: string;
}

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

我希望像update<T>(setting: T)这样的函数在对象中找到T类型的属性,它实现了interface C并更新了setting传递的找到的属性(如果存在的话)。

有没有办法实现这一目标?我试过迭代和typeof但编译器返回This condition will always return 'false' since types 'T' and 'string' has no overlap

typescript
1个回答
1
投票

一个可行的解决方案是传入密钥名称。您可以让编译器检查密钥名称是C的有效密钥,并且value参数与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 
© www.soinside.com 2019 - 2024. All rights reserved.