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 do I need to define prop?
typescript error:TS2339: Property addressSeq does not exist on type
string | number | Date | IpPatientAddressDto | IpPatientRelationshipDto[]
Property addressSeq does not exist on type string
I know the way to write it, but I don’t want to provide extra ways to get it.
const get = <T extends keyof ObjType>(key: T): ObjType[T] => {
return obj[key]
}
let res = get("a"); //"1"
2
Answers
You need to add a key check so the type system can know what the property type is. All it knows is you’re passing a key of
IpPatientInfoDto
but there are other properties that do not have typeIpPatientAddressDto
.Apparently only the property
localAdress
has an object with anaddressSeq
property. What I see is that TS is making you avoid a mistake of accesing a property that may not exist.What you can do is use a Type Guard to check if the object has the shape you expect to have like this:
In that way you check if the property exists first or return a default value if it doesn’t.