我的应用程序后端存在类型问题。该应用程序具有各种患者的数据供医生管理。我正在尝试向现有患者中添加新条目,但出现此错误:
Argument of type '{ type: "Hospital" | "OccupationalHealthcare" | "HealthCheck"; description: string; date: string; specialist: string; diagnosisCodes?: string[] | undefined; id: number; }' is not assignable to parameter of type 'Entry'.
Type '{ type: "Hospital" | "OccupationalHealthcare" | "HealthCheck"; description: string; date: string; specialist: string; diagnosisCodes?: string[] | undefined; id: number; }' is not assignable to type 'HealthCheckEntry'.
Types of property 'type' are incompatible.
Type '"Hospital" | "OccupationalHealthcare" | "HealthCheck"' is not assignable to type '"HealthCheck"'.
Type '"Hospital"' is not assignable to type '"HealthCheck"'.ts(2345)
我检查了所有内容,似乎代码应该可以正常工作。谁能帮我这个?错误在此行上:patientData.find(p => p.id === patientId)?.entries.push(newEntry);
import patientData from '../../data/patients'
import { Patient, NonSensitivePatientData, NewPatient, NewEntry } from '../types';
const patients: Array<Patient> = patientData
const getPatients = (): Patient[] => {
return patients;
};
const addEntry = (entry: NewEntry, patientId: string): Patient | undefined => {
const newEntry = {
id: 1,
...(entry as NewEntry)
}
patientData.find(p => p.id === patientId)?.entries.push(newEntry);
const patient = patients.find(p => p.id === patientId);
console.log(newEntry);
return patient;
}
export default {
addEntry
};
这是我的类型:
interface BaseEntry {
id: string;
description: string;
date: string;
specialist: string;
diagnosisCodes?: Array<Diagnose['code']>;
}
export enum HealthCheckRating {
"Healthy" = 0,
"LowRisk" = 1,
"HighRisk" = 2,
"CriticalRisk" = 3
}
export interface HealthCheckEntry extends BaseEntry {
type: "HealthCheck";
healthCheckRating?: HealthCheckRating;
}
interface Discharge {
date: string;
criteria: string;
}
export interface HospitalEntry extends BaseEntry {
type: "Hospital";
discharge: Discharge;
}
interface SickLeave {
startDate: string;
endDate: string;
}
export interface OccupationalHealthcareEntry extends BaseEntry {
type: "OccupationalHealthcare";
employerName: string;
sickLeave?: SickLeave;
}
export type Entry =
| HospitalEntry
| OccupationalHealthcareEntry
| HealthCheckEntry;
export interface Patient {
id: string;
name: string;
dateOfBirth: string;
ssn: string;
gender: Gender;
occupation: string;
entries: Entry[];
}
export type NewEntry = Omit<Entry, 'id'>;
答案 0 :(得分:0)
我已经弄清楚了:我不得不做“类型断言”。类型“ NewEntry”没有id属性,但是我要向“ entry”添加一个id,此过程将创建newEntry变量。现在,我不得不将其类型从NewEntry更改为Entry,它的发生是这样的:
patientData.find(p => p.id === patientId)?.entries.push(newEntry as Entry);