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?
CodePudding user response:
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
CodePudding user response:
function myFunc(structure: [number, number[]]) {
....
}
This is called a tuple type.