当我尝试将类型 'string' 分配给 @Input 时,类型 'string' 不可分配给类型 'PostCard Layout'

Type 'string' is not assignable to type 'PostCard Layout' when I am trying to assign it to @Input

我遇到了错误

Type 'string' is not assignable to type 'PostCard Layout'

我有一个名为 page-blog.component.html 的 parent 组件,我正在其中设置 class 样式,并将它们传递给名为 post-card.component.ts 的 child 组件

在我的 parent HTML 组件中,当我尝试从 class 组件设置 class 样式变量时,它对我来说是错误的。在 @Input() layout: PostCardLayout; 部分发生。

我发现我觉得是一个肮脏的修复,但通过进入 tsconfig.json 文件并设置 "strictInputTypes": false,

可能会允许我在未来犯更多的错误

Child class post-card.component.ts

import { Component, HostBinding, Input } from '@angular/core';

 export type PostCardLayout = 'list' | 'grid' | 'grid-sm';

 @Component({
  selector: 'app-post-card',
   templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.scss']
 })
export class PostCardComponent {

@Input() post;

@Input() layout: PostCardLayout;

@HostBinding('class.post-card') classPostCard = true;

@HostBinding('class.post-card--layout--list') get classPostCardLayoutList(): boolean {
  return this.layout === 'list';
}

@HostBinding('class.post-card--layout--grid') get classPostCardLayoutGrid(): boolean {
  return this.layout === 'grid';
}

@HostBinding('class.post-card--layout--grid-sm') get classPostCardLayoutGridSm(): boolean {
  return this.layout === 'grid-sm';
}

constructor() { }
}

这里是 parent HTML 组件 page-blog.component.html

                    <div class="posts-list__body">
                        <div *ngFor="let post of posts" class="posts-list__item">
                            <app-post-card
                                [post]="post"
                                [layout]="{
                                    classic: 'grid',
                                    list: 'list',
                                    grid: 'grid-sm'
                                }"
                            ></app-post-card>
                        </div>
                    </div>

您输入的 PostCardLayout 接受以下三个值之一:

'list' | 'grid' | 'grid-sm'

您正试图传递一个 JSON 对象:

[layout]="{
          classic: 'grid',
          list: 'list',
          grid: 'grid-sm'
      }[layout]"

似乎还有一个拼写错误,您输入的末尾多了一个 [layout]

我猜是在输入错误和关闭 strictIputTypes 之间,您的 JSON 正在变形为字符串。

使用 "strictInputTypes": false 是一个糟糕的主意,因为这违背了 TypeScript 的基本目的之一。

从你的代码中我可以看出你只想分配三个 pre-defined 值之一:

<app-post-card
      [post]="post"
      [layout]="'grid'">
</app-post-card>