Typescript-动态分配对象?

问题描述 投票:0回答:2

我对Typescript还是陌生的,老实说,JS之外的任何东西。

我想创建一个类似于JS函数的单个函数

updateField(key, val) {
    this[key] = val
  }

我不知道这在打字稿中是否可以实现。如果这是不应该做的事情并且打破了打字稿的意义,我想我很高兴创建多个函数。

我曾尝试遵循类似问题的其他答案,但碰壁了,不确定是否还有其他尝试。但这就是我最终的归宿。注意:我正在使用mobx,因此使用'this'

即使对为什么无法实现更好的教育感到满意。

export class WhoForSelection {
  @persist @observable label = ''
  @persist @observable value = ''
}

class EQuiz {
  whoFor: WhoForSelection

  fistName: string
  dob: string
  gender: string

  @action
  updateField<T extends keyof EQuiz, K extends EQuiz[T]>(name: T, value: K) {
    this[name] = value
  }
}

有错误的

(parameter) name: T extends "whoFor" | "fistName" | "dob" | "gender" | "updateField"
Type 'K' is not assignable to type 'this[T]'.
  Type 'EQuiz[T]' is not assignable to type 'this[T]'.
    Type 'EQuiz' is not assignable to type 'this'.
      'EQuiz' is assignable to the constraint of type 'this', but 'this' could be instantiated with a different subtype of constraint 'EQuiz'.
        Type 'EQuiz[T]' is not assignable to type 'WhoForSelection &
typescript mobx-react
2个回答
0
投票

您正在测试输入的类型,因此可以在方法中动态地进行操作而没有风险。

class EQuiz {
  firstName: string = '';
  dob: string = '';
  gender: string = '';
  test: number = 0;

  updateField<T extends keyof EQuiz, K extends EQuiz[T]>(name: T, value: K) {
    this[name] = value as any;
  }
}

const quiz = new EQuiz();

quiz.updateField("firstName", "name");
quiz.updateField("test", 1);

自动完成功能告诉您,“ firstName”需要提供一个字符串,而“ test”需要提供一个数字。鉴于此方法签名的“锁定”性质,您需要确定它是否比quiz.firstName = "name"赋予您特定的好处。

如果您打算让字符串成为动态字符串,则您将立即失去类型安全性,因为编译器将不知道动态字符串是有效的选择,还是用于类型安全性的选择。这样,您的签名也可能会简单得多,并且您可能需要让该方法检查密钥是否有效。


0
投票

问题是TypeScript认为您想更新EQuiz的任何属性,包括updateFieldupdateField需要访问this,并且需要this属于EQuiz类型。

在这种情况下,TypeScript要求您明确声明updateField需要特定的this

// Notice the "this" as the first argument
updateField<T extends keyof EQuiz, K extends EQuiz[T]>(this: EQuiz, name: T, value: K) {
  this[name] = value;
}

您可以在this中阅读有关TypeScript handbook类型的更多信息>

© www.soinside.com 2019 - 2024. All rights reserved.