typescript 如何声明两个数字元组的返回类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45146318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:43:18  来源:igfitidea点击:

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

typescript

提问by ave

When I declare a function as

当我将函数声明为

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

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

我得到的错误是 [ts] Duplicate identifier 'number'.

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

如果我省略返回值的类型签名,那么它会将其推断为 number[]

回答by Tom Cumming

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

No need for the parenthesis around the return tuple type

不需要围绕返回元组类型的括号

回答by Alexandre Hitchcox

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

From TypeScript 3.4 onwards you can use const assertations.

从 TypeScript 3.4 开始,您可以使用 const 断言。