【问题标题】:When using Angular @Input decorator, Typescript Type 'string' is not assignable to type使用 Angular @Input 装饰器时,Typescript Type \'string\' 不可分配给类型
【发布时间】:2022-11-15 13:28:15
【问题描述】:

** 我的问题与角度 @Input () 装饰器有关,因为当我使用此装饰器时,打字稿抛出错误,而不是在常规代码中使用时。

在我的 child.component.ts 文件中,我声明这个装饰器从父组件获取道具:

  @Input() customColumns: {
    name: string;
    index: number;
    type: 'icon' | 'image' | 'link' | 'button';
    icon?: any;
    url?: string;
  }[] = [];
  indexList: number[] = [];

在我的 parent.component.ts 文件中,我正在为这个变量分配值,如下所示:-

  customColumns = [
    { name: 'permissions', index: 7, type: 'icon', icon: faSave },
    { name: 'price list', index: 6, type: 'link', icon: faArrowDownWideShort },
    { name: 'details', index: 5, type: 'button', icon: faArrowUpWideShort },
  ];

最后,在我的 parent.component.html 文件中,我调用了该子组件:-

      <app-child [customColumns]="customColumns">
      </app-child>

但得到这个错误: -

Types of property 'type' are incompatible.
      Type 'string' is not assignable to type '"button" | "link" | "image" | "icon"'.

但是当我在正常的打字稿或 ngOnInit() 函数中做同样的事情时,它正在工作,无法弄清楚为什么会发生,请帮助我,在此先感谢。

    let customColumns: {
      name: string;
      index: number;
      type: 'icon' | 'image' | 'link' | 'button';
      icon?: any;
      url?: string;
    }[] = [];

    customColumns = [
      { name: 'permissions', index: 7, type: 'link', icon: '' },
      {
        name: 'price list',
        index: 6,
        type: 'icon',
        icon: faArrowDownWideShort,
      },
      { name: 'details', index: 5, type: 'icon', icon: faArrowUpWideShort },
    ];

我的项目依赖项:

"@angular/cli": "~14.2.7",
"typescript": "~4.7.2"

【问题讨论】:

  • 你可以设置 type?:any
  • 我可以,但我想限制一下,其他人只能分配 4 个选项或字符串值。

标签: angular typescript


【解决方案1】:

请试试这个

let customColumns: {
  name: string;
  index: number;
  type: "icon" | "image" | "link" | "button";
  icon?: any;
  url?: string;
}[] = [];

【讨论】:

  • 正如你提到的,我已经做过同样的事情。正如我在问题中所描述的那样,它正在工作,但在我使用 @Input () 而不是 let 时不起作用。
【解决方案2】:

为了在普通 TypeScript 中复制相同的行为,您应该使用以下场景:

let customColumns: {
  name: string;
  index: number;
  type: 'icon' | 'image' | 'link' | 'button';
  icon?: any;
  url?: string;
}[] = [];

const anotherValue =  [
  { name: 'permissions', index: 7, type: 'link', icon: '' },
  {
    name: 'price list',
    index: 6,
    type: 'icon',
  },
  { name: 'details', index: 5, type: 'icon', icon: '' },
];
customColumns = anotherValue;

这类似于 Angular 类型检查代码。

为了解决它,您可以使用任一预定义的枚举:

const enum ColumnType {
  icon = 'icon',
  image = 'image',
  link = 'link',
  button = 'button',
}

let customColumns: {
  name: string;
  index: number;
  type: ColumnType;
  icon?: any;
  url?: string;
}[] = [];


...
type: ColumnType.link,

as const:

type: 'link' as const

【讨论】:

  • type: 'link' as const,我不能用角度来做,我必须为它声明接口。我的问题不是普通的打字稿,而是有角度的@Input(),它不起作用。不过还是谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2021-11-16
  • 2022-07-27
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多