如果我要创建一个简单的对象,如下面的类型,我想创建一个函数,该函数接受对象、对象的有效键和基于对象键的值的类型的有效值.
export interface MyType {
prop1: string;
prop2?: number;
prop3?: string[];
}
我发现我可以很容易地使用keyOf MyType方法输入更新函数,从而只允许类型的有效属性.
propertyName: keyOf MyType;
个
我还发现,我可以通过访问键上的类型来输入值.下面的代码应该是一个字符串.
propertyValue: MyType["prop1"];
个
然而,我在使用所有可能的键--pro1、pro2和pro3--键入PropertyValue时遇到了麻烦.
export interface MyType {
prop1: string;
prop2?: number;
prop3?: string[];
}
const instanceOfMyType: MyType = {
prop1: "hello"
}`
const updatePropOfMyType = (thingBeingUpdated: MyType,
propertyName: keyof MyType,
propertyValue: MyType[typeof propertyName]): MyType
=>{
const updatedType = _.cloneDeep(thingBeingUpdated);
updatedType[propertyName] = propertyValue;
return updatedType;
};
Expected output:
const updatedInstanceOfMyType = updatePropOfMyType(instanceOfMyType, "prop2", 123);
console.log(updatedInstanceOfMyType)
// Expecting output {prop1: 'hello", prop2: 123}`
类似
const anotherUpdatedInstanceOfMyType = updatePropOfMyType(instanceOfMyType, "prop2", "hi");
//should give me a type error since prop2 is a number not a string;
Actual output
相反,我有一个类型错误 "类型‘STRING|NUMBER|STRING[]|UNDEFINED’不可分配给类型‘Never’. 类型‘unfined’不可赋值给类型‘Never’."at the updatdType[PropertyName]=PropertyValue;
这似乎是因为TypeScrip将MyType属性的所有可能类型连接在一起,而不是为当前设置的PropertyName值过滤类型.
我只是想看看是否有一种方法可以动态地强制PropertyValue的类型与基于当前设置的PropertyName;的值的给定属性相同;