0

I need to pass data with the structure shown below

export const Legend = ({ data }: { data: [string, number][] }) => ....

Why Typescript types test array in the way like in picture (string | number)[][], instead of [string, number][]

enter image description here

Of course, I can overwrite the type, but I do not think this is a good approach

2
  • 3
    If your question is really "why does Typescript do this?", the answer is because if it inferred [string, number] instead of (string | number)[] for an array containing a string and a number, a lot more people would be annoyed about it. Consider using a different type like {s: string, n: number}, or just write the type annotation. Commented Jul 30, 2022 at 15:11
  • Please replace/supplement images of code/errors with plaintext versions. Commented Jul 30, 2022 at 20:16

1 Answer 1

3

No, it is your side issue. [string, number][] is an array whose elements are string and number pair. I assume you'd like to type test more specific than (string | number)[][] (NOTE: If so, it is called XY-problem, which you should avoid).

You may want to use const-assertion, which can be done by postfix expression by as const, like this:

const test = [
    ['C2B', 'D2C', 'PDP', 1],
    ['C2B', 'D2C', 'PDP', 2],
    ['C2B', 'D2C', 'PDP', 4],
    ['C2B', 'D2C', 'PDP', 2],
] as const;

You should change Legend signatures, too:

export const Legend = ({ data }: { data: readonly (readonly [string, string, string, number])[] }) => ...

The test elements are typed an specific type which is subtype of readonly [string, string, string, number]. The outer readonly modifier means entire array is read-only and you cannot change its contents. This is side effect of const-assertion, which does not have opt-out way.

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.