0

I have the following data structure which I want to pass as a parameter into a function.

let structure = [6, [197,47,28,191,198,129,117,82,171]]

It's given that the first element is always a number and the second element an array of numbers. When I want to pass it to my function, my IDE suggests following as input types:

function myFunc(structure:(number | number[])[]) {
    ....
}

This leads to problems because it is not specific enough. I know the first element is always a number, but based on my type declaration it doesn't have to be.

How do you declare the type here properly in typescript?

3
  • 4
    Use a tuple: [number, number[]] Commented Feb 24, 2022 at 11:10
  • It has to be an array? Why not an object (e.g. { id : number; data : number[] })? Commented Feb 24, 2022 at 11:15
  • The array was given. Now I found out that's acutally a tuple type. I was able to sove it now. Thank you very much! Commented Feb 24, 2022 at 19:45

2 Answers 2

2

I would specify it as a type

type MyStructure = [number,number[]] // give it a better name than MyStructure!

and use that for the function argument

function myFunc(structure:MyStructure) {
    ....
}

Playground link showing that it constrains the inputs to what you wanted

Sign up to request clarification or add additional context in comments.

Comments

1
function myFunc(structure: [number, number[]]) {
    ....
}

This is called a tuple type.

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.