6

I'd like to define a typed array, specifying a type for the first element, another type for the second and so on...

In fact, I'm trying to get rid of the following casts:

const cases = [
  [ 'http://gmail.com', false ],
  [ '/some_page', true ],
  [ 'some_page', false ]
]

describe("'isInternalLink' utility", () => {
  test.each(cases)(
    "given %p as argument, returns %p", (link, result) => {
      expect(
        isInternalLink(<string>link)
      ).toEqual(
        <boolean> result
      )
    }
  )
})

As you can see, each element in cases is an array which has a string as first element and a boolean as second...

Just to be clear, I don't want an array of string | boolean type, I want an array whose first element is a string and whose second element is a boolean.

Any idea how to improve this???

3
  • 1
    Use casses = [..... ] as const Commented Sep 9, 2019 at 3:23
  • 1
    Interesting, as const doesn't work right in this case (at least in my vscode). I wonder if the typing for test.each needs some work? @TitianCernicova-Dragomir Commented Sep 9, 2019 at 3:42
  • I get this error: Type 'readonly ["gmail.com", false]' is not assignable to type 'string'. What a shame, that would have been the perfect solution to this problem Commented Sep 9, 2019 at 3:43

1 Answer 1

6

cases is an Array, and each element in cases is a Tuple, so if you define cases like this:

const cases: [string, boolean][] = ...

...or alternatively like this:

const cases: Array<[string, boolean]> = ....

...then link will be a string and result will be a boolean and your test can be simplified to this:

describe("'isInternalLink' utility", () => {
  test.each(cases)(
    "given %p as argument, returns %p", (link, result) => {
      expect(isInternalLink(link)).toEqual(result)
    }
  )
})
Sign up to request clarification or add additional context in comments.

2 Comments

YES, exactly what I was looking for (too bad the as const option wouldn't work in this scenario...)
can I use this while inside another interface?

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.