简体   繁体   English

打字稿中动态访问的属性的类型

[英]type of dynamically accessed property in typescript

I have a function I want to reuse that is applicable on multiple properties of a custom type.我有一个我想重用的函数,它适用于自定义类型的多个属性。 Something like this:像这样的东西:

interface MyType {
  prop1: string;
  prop2: number;
}
type MyTypeKey = keyof MyType;

const testValue = (
  obj: MyType,
  property: MyTypeKey,
  value: any, // <-- what type should go here?
) => {
  if (obj[property] === value) {
    console.log("do something");
  }
}

testValue({prop1: "a", prop2: 1}, "prop1", "okay"); // should be okay
testValue({prop1: "a", prop2: 1}, "prop2", "oops"); // should be error

But I don't know how to do this since I don't know the type of the property value.但我不知道该怎么做,因为我不知道属性值的类型。 How can I solve this?我该如何解决这个问题?

(I am new to javascript/typescript, so forgive me for small typos and constructions and bad practices) (我是 javascript/typescript 的新手,所以请原谅我的小错别字和结构以及不良做法)

Use a generic argument to indicate the key.使用通用参数来指示键。 From that key you can look it up on MyType to get the associated value's type, and require that the value argument to the generic function be that type.通过该键,您可以在MyType上查找它以获取关联值的类型,并要求泛型函数的value参数是该类型。

interface MyType {
    prop1: string;
    prop2: number;
}

const testValue = <K extends keyof MyType>(
    obj: MyType,
    property: K,
    value: MyType[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}

declare const obj: MyType;
// OK
testValue(obj, 'prop2', 3);
// Not OK
testValue(obj, 'prop2', 'a');

For a more flexible function that can validate any sort of object, without hard-coding MyType into it, make another generic type for the object.对于可以验证任何类型的对象的更灵活的函数,无需将MyType硬编码到其中,请为该对象创建另一个泛型类型。

const testValue = <O extends object, K extends keyof O>(
    obj: O,
    property: K,
    value: O[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM