SakthiSureshAnand
SakthiSureshAnand

Reputation: 1362

Typescript string | string[] find the array length

I am finding the length of string|string[] , I have variable as a data type of var stepData : string | string[] . Some times I am getting a single string value , also possible to get the list of string . Using the length of array I am doing some other operation. In my code I am doing some for loop function using that stepData.length . Here the sample my code

const stepData: string|string[] = this.$stateParams.stepData;

 // Here two possible length value I am getting 
 // If the stepData is string[] get length of array value 
 // If the stepData is string  get the length of string
 // The `lengthVar` depends on below for loop

 if (stepData.length > 0) {
        var lengthVar = stepData.length;
     for (var i = 0; i < lengthVar; i++) {
          // Inside im writing some ajax call
     }
 }

How to find the exact array length of stepData I want array value only using I am calling AJAX method inside . If any suggest I am trying any wrong or give ur valuable suggestions please.

Upvotes: 0

Views: 7322

Answers (4)

If you want to know if some variable is a string or string[] you could use the keyword instanceof:

if(stepData instanceof Array<string>) {
...
} else {
...
}

or

if(typeof stepData === "string") {
...
} else {
...
}

Upvotes: 1

Mattias Buelens
Mattias Buelens

Reputation: 20159

From your comment on the question:

Inside for I am iterating stepData.length . So If its string only one time I should iterate ,If its string[] I should find the length of string array that much time I iterate

In that case, your code must be able to differentiate between string and string[] with a check at runtime. A simple check to differentiate between the two would be typeof stepData === "string", which will be true for strings but false for string[]s.

if (typeof stepData === "string") {
    // here stepData is a string
} else {
    // here stepData is a string[]
}

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

You're questions is very unclear, but I'll take a guess that you're asking how to know whether the value in stepData is a string or string[], if that the case then:

if (typeof stepData === "string") {
    // stepData is a string
} else { 
    // stepData is a string[]
}

or

if (stepData instanceof Array) {
    // stepData is a string[]
} else { 
    // stepData is a string
}

You can make your stepData not a const and then:

let stepData: string|string[] = this.$stateParams.stepData;

if (typeof stepData === "string") {
    stepData = [stepData];
}

// now stapData is string[]

Upvotes: 1

AlexG
AlexG

Reputation: 4045

Just do something like:

const _stepData = (typeof stepData === 'string') ? [stepData] : stepData;

then iterate it as an Array. More consistent, less bugs.

Upvotes: 1

Related Questions