英文:
What's the difference when setting the type like these?
问题
const example : type = () => {}
const example = () : type => {}
它们有区别吗?
如果它们有区别,我该如何设置类型为 () => {}
?
() : type => {}
正确吗?
英文:
const example : type = () => {}
const example = () : type => {}
Are they different?
if they are different, how can i set type () => {}
?
() : type => {}
Is it correct?
答案1
得分: 1
是的。
const example: type = () => {}
这声明了一个名为 example
的变量,类型为 type
。由于我们正在将一个函数分配给它,类型 type
最好是一个函数类型(比如 () => void
),或者与函数类型兼容的东西(比如 any
或 `unknown)。
const example = (): type => {}
这声明了一个名为 example
的变量(其类型被推断)。该变量的值是一个函数,该函数返回一个类型为 type
的值。由于函数体明显不返回任何内容,type
最好是 void
(或者如果关闭了 noImplicitReturns
,则是 undefined
)。
在第一种情况下,type
是整个函数的类型。在第二种情况下,它是从函数返回的值的类型。
英文:
Yes.
const example : type = () => {}
This declares a variable example
of type type
. Since we're assigning a function to it, the type type
had better be a function type (like () => void
), or something compatible with a function type (like any
or unknown
).
const example = () : type => {}
This declares a variable called example
(whose type is inferred). The value of that variable is a function which returns a value of type type
. Since the function body clearly doesn't return anything, type
had better be void
(or undefined
if noImplicitReturns
is off).
In the first case, type
is the type of the entire function. In the second, it's the type of the return value from the function.
答案2
得分: 0
两种提供的语法都是在TypeScript中声明函数类型的有效方式。
第一种:
const example: type = () => {}
这种语法声明了一个名为example的常量变量,其类型是type,它是一个不带参数并返回值的函数类型。
第二种:
const example = (): type => {}
这种语法声明了一个常量变量example,并使用函数类型注解来定义其类型。它指定example是一个不带参数并返回类型为type的函数。
如果你的函数带有参数,可以像这样声明:
let example: (x: type, y: type) => type;
如果你的函数不带参数且返回void,可以这样声明:
let example: Function;
英文:
Both syntaxes that you provided are valid ways to declare a function type in TypeScript.
the first one:
const example : type = () => {}
This syntax declares a constant variable example of type type, which is a function type that takes no parameters and returns a value.
and second one:
const example = () : type => {}
This syntax declares a constant variable example and defines its type using a function type annotation. It specifies that example is a function that takes no parameters and returns a value of type type.
if you used further with parameters the do this:
let example: (x: type, y: type) => type;
if your function is returns void without parameters do this:
let example : Function;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论