-1

I have variable with a type as

let campaigns : {
  [key: string] : string[]
} | string[] = []

As we can see in a logic variable is either one or another type. When I know for sure in my logic that is an array I will try to use as campaigns.push("string"). But I will get Typescript error as saying that you can't use push on object, cause typescript doesn't know that in my logic I illuminated a chance on been an object. How let Typescript know that campaign.push() is a legal operation ?

1 Answer 1

2

please do like this:

const arrOrObj: Record<string, string> | string[] = []

if (Array.isArray(arrOrObj)) arrOrObj.push("a")

Or you can use a type checking function:

function isArrayString(arr: object): arr is string[] {
  return typeof arr === "object" && "length" in arr
}

is allows you to specify how the type of a variable is defined. That is, when the function returns true, the variable declared on the left will have the type on the right. That is when

if (isArrayString(arr)) {
  // arr is string[] <-- The type that `is` specifies in the return . declaration
} else {
  // arr is other type
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.