0

I wrote some code in Typescript:

for (const [a, b] of [['1', 2],['3', 4]]) {
  console.log(a.substr(0));
}

In javascript, it works, and outputs:

1
3

But in Typescript,that will cause an compile error near substr:

TS2339: Property 'substr' does not exist on type 'string | number'.   Property 'substr' does not exist on type 'number'.

Seems like the compiler cannot confirm the type of a, from string/number.

I think it's a bug of TypeScript. Am I wrong? Or if there is a better way to do this?

1 Answer 1

1

It's not a bug. Basically, when you write ['1', 2], Typescript will understand it as <string | number>[] instead of [string, number]. So if you want to force it to [number, string], you have to define the type

  for (const [a, b] of <[string, number][]>[['1', 2],['3', 4]]) {
    console.log(a.substr(0));
  }
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.