2

在下面的代码中,typscript 编译器在更新方法中显示错误,说“任何”不能分配给“从不”类型。我注意到当类型包含与其他类型混合的布尔值时,keyof 类型不起作用。我怎样才能使它编译在类型中有混合类型值?

type ConfigState = {
  isAdminSet: boolean;
  isDatabaseConnected: boolean;
  adminName: string;
};

export class ConfigManager {
  state: ConfigState = {
    isAdminSet: false,
    isDatabaseConnected: false,
    adminName: "",
  };

  update(key: keyof ConfigState, value: ConfigState[keyof ConfigState]) {
    this.state[key] = value;
  }
}

但这编译:

type ConfigState = {
  isAdminSet: boolean;
  isDatabaseConnected: boolean;
};

export class ConfigManager {
  state: ConfigState = {
    isAdminSet: false,
    isDatabaseConnected: false,
  };

  update(key: keyof ConfigState, value: ConfigState[keyof ConfigState]) {
    this.state[key] = value;
  }
}
4

1 回答 1

2

TLDR:TypeScript 不知道您value是否适合state.

在您的第一个示例中,所有属性都是boolean,因此any推断为boolean。但是,一旦您添加了其他类型(此处为 a string),any就无法在不限制key. 因此,它被推断为never,并且您不能分配anynever

在这种情况下,您必须(我认为)为此使用泛型。此外,这将确保类型安全。

查看 TS 文档的这一部分:https ://www.typescriptlang.org/docs/handbook/2/generics.html#using-type-parameters-in-generic-constraints

type ConfigState = {
  isAdminSet: boolean;
  isDatabaseConnected: boolean;
  adminName: string;
};

export class ConfigManager {
  state: ConfigState = {
    isAdminSet: false,
    isDatabaseConnected: false,
    adminName: "",
  };

  update<Key extends keyof ConfigState>(key: Key, value: ConfigState[Key]) {
    this.state[key] = value;
  }
}
于 2021-11-10T16:54:52.207 回答