Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a return type of a tuple of two numbers?

Tags:

typescript

When I declare a function as

const coordinates = (id: number): ([number, number]) => {

the error I get is [ts] Duplicate identifier 'number'.

If I omit type signature for return value, then it infers it as number[]

like image 782
ave Avatar asked Jul 17 '17 14:07

ave


People also ask

How do I return tuples values?

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x//y and then x%y .

Which of the following Python statements will return a tuple of two values from a function?

A Python function can return any object such as a tuple. To return a tuple, first create the tuple object within the function body, assign it to a variable your_tuple , and return it to the caller of the function using the keyword operation “ return your_tuple “.

How do you define a tuple in TypeScript?

A tuple is a TypeScript type that works like an array with some special considerations: The number of elements of the array is fixed. The type of the elements is known. The type of the elements of the array need not be the same.


2 Answers

const coordinates = (id: number): [number, number] => [id, id];

No need for the parenthesis around the return tuple type

like image 89
Tom Cumming Avatar answered Oct 03 '22 06:10

Tom Cumming


const coordinates = (id: number) => [id, id] as const;
// const coordinates: (id: number) => [number, number]

From TypeScript 3.4 onwards you can use const assertations.

like image 28
Alexandre Hitchcox Avatar answered Oct 03 '22 06:10

Alexandre Hitchcox