![](/img/trans.png)
[英]Property '...' is missing in type 'ReactElement<any, any>' but required in type '{...}'
[英]Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }]
這是界面的樣子
export interface Patient {
doctors: [{
id: null,
gp: null,
}]
}
這是我的元組
linkedDoctorShort: Array<any> = []; // will contain only the ID and GP
我嘗試了一些在StackOverflow上找到的解決方案,但是仍然遇到相同的錯誤,尤其是當我想保存所有信息時:
onSave() {
const patientInfo: Patient = {
doctors: this.linkedDoctorShort,
};
錯誤信息 :
類型“ any []”中缺少屬性“ 0”,但是類型“ [{{id:string; gp:布爾值; }]'。
謝謝您的幫助
linkedDoctorShort: Array<any> = [];
不是元組。 它是一個用空數組初始化的數組。
如果您希望它是一個數組( doctors
可以有任意數量的元素),請在界面中使用數組類型
export interface Patient {
doctors: Array<{
id: null,
gp: null,
}>
}
如果只需要一個元素(即長度為1的元組)。 然后將其用於linkedDoctorShort
類型,並相應地linkedDoctorShort
進行初始化:
export interface Patient {
doctors: [{
id: null,
gp: null, // are you sure these can only be null ? I think you mean soemthing like string | null
}]
}
let linkedDoctorShort: [any] = [{ id: null, gp: null }]; // Or better yes let linkedDoctorShort: [Patient['doctors'][0]] to keep type safety
const patientInfo: Patient = {
doctors: this.linkedDoctorShort,
};
將界面更改為:
export interface Patient {
doctors: Array<{id: string;gp: boolean;}>;
}
但是我不是內聯打字的忠實粉絲。 我喜歡更簡潔的語法,例如:
export interface Doctor {
id: string;
gp: boolean;
}
export interface Patient {
doctors: Doctor[];
}
盡管您遇到錯誤,但建議是明確的類型定義。
export interface Doctor {
id: string | number;
gp: boolean;
}
export interface Patient {
doctors: Doctor[];
}
就像@jpavel所說的。 那么您可以利用Typescript的優勢。
const linkedDoctorShort:Doctor[] = [];
onSave() {
const patientInfo: Patient = {
doctors: this.linkedDoctorShort,
};
你不會錯過的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.