【问题标题】:How to safely refer to a parameterised property of an object in Typescript?如何在 Typescript 中安全地引用对象的参数化属性?
【发布时间】:2021-10-08 00:58:53
【问题描述】:

我有一个函数,它接收一个对象作为参数并访问它的一个属性,由另一个参数确定。像这样的:

// js code
function setProperty(subject, property, value) {
    subject[property] = value;
}

我如何对该函数进行类型注释,以确保property 参数是subject 参数的键,并且value 参数具有相同的类型?

如果有帮助,我希望 property 参数始终是文字值(“硬编码”值,而不是变量),所以这是一个可以接受的约束。

【问题讨论】:

    标签: typescript type-annotation


    【解决方案1】:

    您可以使用泛型、extendskeyof 来实现此类功能。例如:

    interface Subject {
        a: string,
        b: number
    }
    
    function setProperty<T extends keyof Subject>(subject: Subject, property: T, value: Subject[T]) {
        subject[property] = value;
    }
    
    const test: Subject = { a: 'test', b: 2 };
    
    setProperty(test, 'b', 'test'); // Won't compile: Argument of type 'string' is not assignable to parameter of type 'number'.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2017-08-08
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多