interface IpPatientAddressDto {
...
addressSeq: number;
}
interface IpPatientInfoDto {
...
localAddress: IpPatientAddressDto;
}
const originalPatient:IpPatientInfoDto = {
...
localAddress:{
addressSeq:0001
}
}
const createAddrCollectionObj = (prop: keyof IpPatientInfoDto) => {
return {
addressSeq: originalPatient[prop].addressSeq, // error:TS2339
}
}
const a1 = createAddrCollectionObj('localAddress');
How should I define the prop parameter correctly?
Error in typescript: TS2339: Property 'addressSeq' does not exist on type string | number | Date | IpPatientAddressDto | IpPatientRelationshipDto[]. Property 'addressSeq' does not exist on type string.
I have an idea of how to solve it, but I want to avoid unnecessary complexity.
const get = <T extends keyof ObjType>(key: T): ObjType[T] => {
return obj[key]
}
let res = get("a"); //"1"
I am thinking that createAddrCollectionObj should be constrained by the type of the prop parameter, and it must have access to other properties such as addressSeq.
When calling createAddrCollectionObj('xxx'), Typescript should be able to verify if xxx matches the corresponding type.
const createAddrCollectionObj = (prop: keyof IpPatientInfoDto) => {
const property = originalPatient[prop];
if (!isIpPatientAddressDto(property,prop)) {
return null;
}
return {
addressSeq: property.addressSeq,
patientSeq: property.patientSeq,
address: patInfo[prop + 'Details'],
provinceCode: patInfo[prop][0].code,
provinceName: patInfo[prop][0].name,
cityCode: patInfo[prop][1].code,
cityName: patInfo[prop][1].name,
areaCode: patInfo[prop][2].code,
areaName: patInfo[prop][2].name,
zipCode: '', // 邮编
};
};