我不明白为什么在我的Angular 项目中,当我试图将值设置为testObject时,打字错误Type boolean is not assignable to type never.

export interface TestInterface {
  text: string;
  number: number;
  bool1: boolean;
  bool2: boolean;
}

export class DamagesComponent implements OnInit {
  testObject: TestInterface = {
    text: 'test String',
    number: 22,
    bool1: false,
    bool2: true
  }

  ngOnInit() {
    this.toogleVal('bool1')
  }

  toogleVal(key: keyof TestInterface): void {
    if (key in this.testObject) {
      if (typeof this.testObject[key] === 'boolean') {
        // here the error
        this.testObject[key] = true;
      }
    }
  }
}

推荐答案

当你动态访问属性时,你需要在接口中指定键将是一个字符串,返回类型将是一些数据类型,错误将通过修改接口来消除.

export interface TestInterface {
  text: string;
  number: number;
  bool1: boolean;
  bool2: boolean;
  // this needs to be at the bottom for it to accept the default datatypes of the properties set already!
  [key: string]: string | boolean | number;
  // [key: string]: any; // or with any data type which is less preferred!
}

Online Typescript editor

Typescript相关问答推荐

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

Typescript:将内部函数参数推断为子对象键的类型

您可以创建一个类型来表示打字员吗

在Typescribe中,extends工作,但当指定派生给super时出错""

如何为父类构造函数中的修饰属性赋值?

如何在Typescript 中输入两个相互关联的变量?

如何在typescript中设置对象分配时的键类型和值类型

用于验证字符串变量的接口成员

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

在VSCode中显示eslint错误,但在终端中运行eslint命令时不显示?(Vite,React,TypeScript)

Angular material 无法显示通过API获取的数据

为什么我的导航在使用Typescript的React Native中不起作用?

我怎样才能正确地输入这个函数,使它在没有提供正确的参数时出错

将超类型断言为类型脚本中的泛型参数

如何扩展RxJS?

如何以类型安全的方式指定键的常量列表,并从该列表派生所挑选的接口?

Select 类型的子项

如何在Vue动态类的上下文中解释错误TS2345?

必须从注入上下文调用Angular ResolveFn-inject()

Select 器数组到映射器的Typescript 泛型