Home > Mobile >  How to access a Object's variables in Typescript?
How to access a Object's variables in Typescript?

Time:10-25

Cannot get Object's variables, which is returned by calling a single function getParticipants(), which returns from a JS file:

return {
        participantNames,
        participantUniqueNums,
    };

Calling with in a TS file:

const participantsObj = retrieveParticipants.getParticipants();
        
this.d_participantNames = participantsObj.participantNames;
this.d_participantUniqueNums = participantsObj.participantUniqueNums;

Getting: Property 'participantNames' does not exist on type 'Object'.ts(2339)

First experience with TS, not sure how to process this Object

CodePudding user response:

For this to work as per the type checking TS provides, define an interface that you will be using for every participant object and use it both - in your function and in your variable to enable type-checking at both ends

Sample Code :


// Interface
interface Participant {
  participantNames :any,
  participantUniqueNums:any,
}

const getParticipants=(args:any):Participant => {

   // ...... your function's inner code


   return {
        participantNames,
        participantUniqueNums,
    };
}

const participantsObj:Participant = retrieveParticipants.getParticipants();

this.d_participantNames = participantsObj.participantNames;
this.d_participantUniqueNums = participantsObj.participantUniqueNums;


Also when in doubt, feel free to skip type checking like you could have done here (but this is not advisable as it defeats the point of using TS)

Code to skip type checking (try to avoid as much as possible):

const participantsObj = retrieveParticipants.getParticipants() as any

CodePudding user response:

I started studying typescript recently myself, basically what you gotta do is define the type of the object you're passing back, or cast it to a known type using 'as'.

so on your line

const participantsObj = retrieveParticipants.getParticipants();

should be

const participantsObj = retrieveParticipants.getParticipants() as KnownType;

then it would know the Object type. Right now I think its just any type. Maybe you could try make it as any;

CodePudding user response:

try returning the result like this.

return {
        participantNames : value,
        participantUniqueNums : value
    };
  • Related