问题描述
我在这里检查了 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md ,它是 TypeScript语言规范,但我我看不到如何声明函数的返回类型的事情.
I checked here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md which is the TypeScript Language Specifications but I couldn't see one thing that how I can declare a return type of the function.
我在下面的代码中显示了我的期望: greet(name:string):字符串{}
I showed what I was expecting in the code below: greet(name:string): string {}
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(): string {
return "Hello, " + this.greeting;
}
}
我看到我们可以使用(name:string)=>任何
,但它们通常在传递回调函数时使用:
I see we can use something (name:string) => any
but they are used mostly when passing callback functions around:
function vote(candidate: string, callback: (result: string) => any) {
// ...
}
推荐答案
您是正确的-这是一个完全正常的示例-您会看到 var result
是隐式的字符串,因为返回类型在 greet()
函数上指定.将类型更改为 number
,您将收到警告.
You are correct - here is a fully working example - you'll see that var result
is implicitly a string because the return type is specified on the greet()
function. Change the type to number
and you'll get warnings.
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() : string {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("Hi");
var result = greeter.greet();
这是数字示例-如果您尝试执行以下操作,则在游乐场编辑器中会看到红色的花形:
Here is the number example - you'll see red squiggles in the playground editor if you try this:
greet() : number {
return "Hello, " + this.greeting;
}
这篇关于如何在TypeScript中声明函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!