我收到錯誤
型別“字串”不可分配給型別“明信片布局”
我有一個名為的父組件page-blog.component.html,我在其中設定類樣式,并將它們傳遞給名為的子組件post-card.component.ts
在我的父 HTML 組件中,當我嘗試從類組件設定類樣式變數時,它對我來說是錯誤的。部分發生@Input() layout: PostCardLayout;。
我發現我覺得這是一個骯臟的修復,但通過進入 tsconfig.json 檔案并設定,我可能會在未來犯更多錯誤"strictInputTypes": false,
兒童班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() { }
}
這是父 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>
uj5u.com熱心網友回復:
您已鍵入 PostCardLayout 以接受以下三個值之一:
'list' | 'grid' | 'grid-sm'
您正在嘗試傳遞 JSON 物件:
[layout]="{
classic: 'grid',
list: 'list',
grid: 'grid-sm'
}[layout]"
似乎還有一個錯字,因為[layout]您的輸入末尾有一個額外的內容。
我在錯字和關閉嚴格輸入型別之間猜測你的 JSON 正在變成一個字串。
using"strictInputTypes": false是一個糟糕的想法,因為這違背了 TypeScript 的基本目的之一。
從我從您的代碼中可以看出,您只想分配三個預定義值之一:
<app-post-card
[post]="post"
[layout]="'grid'">
</app-post-card>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479141.html
標籤:javascript 有角度的 打字稿
