skip to Main Content

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


  1. 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 type IpPatientAddressDto.

    const createAddrCollectionObj = (prop: keyof IpPatientInfoDto) => {
        switch (prop)
        {
            case 'localAddress': // originalPatient['localAddress'] is IpPatientAddressDto
                return {
                    addressSeq: originalPatient[prop].addressSeq,
                };
            // other cases...
            default:
                return {
                    addressSeq: null,
                };
        }
     };
    
    Login or Signup to reply.
  2. Apparently only the property localAdress has an object with an addressSeq 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:

    function isIpPatientAddressDto(obj: IpPatientInfoDto[keyof IpPatientInfoDto]): obj is IpPatientAddressDto {
      return obj.hasOwnProperty('addressSeq');
    }
    
    const createAddrCollectionObj = (prop: keyof IpPatientInfoDto) => {
      const property = originalPatient[prop];
      if (!isIpPatientAddressDto(property)) {
        return {
          addressSeq: defaultValue, //defaultValue needs to be defined elsewhere   
        };
      }
    
      return {
        addressSeq: property.addressSeq   
      }
    }
    
    const a1 = createAddrCollectionObj('localAddress'); 
    
    

    In that way you check if the property exists first or return a default value if it doesn’t.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search