功能与功能名称()的区别:键入打字稿
问题描述:
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
return counter;
}
请看上面的代码中的第2行。为什么我不能这样做function (start: number): Counter
。<Type>功能与功能名称()的区别:键入打字稿
我想什么,我问的是diffrence <type>
和:type
答
:type
之间 - 是函数的返回值类型的声明。例如:
let counter = function (start: number): number {}
let result = counter(1);
这里,result
变量的类型将是number
。
详情请参阅function types。
<type>
- 是一个type assertion,这意味着它告诉编译器该断言之后的值是指定的类型。在你的情况中,变量counter
将有类型Counter
。
答
你应该看看这个page从打字稿手册。 “断言”一章解释了<Type>
语法。本书对了解TypeScript的基础知识非常有用。
所以基本上:Type
语法用于状态的变量是哪种类型。例如:
let example: string = "This is a string";
let exampleNumber: number = 12;
但请记住,可以推断出许多TypeScript类型。
let example = "This is a string";
let exampleNumber = 12;
有时打字稿代码给你一个any
类型:那么这个代码将有同样的结果。这实际上意味着它可以是任何东西。使用and:Type语法,您将能够将其作为强类型变量进行威胁。因此代码将如下所示:
function test(arg: any): number {
// Threat the arg variable as string;
let example: string = arg;
// Threat the arg variable as string by using Type assertion.
let otherExample = <string> arg;
// Returns arg but the return type = :number so the caller will have a number variable.
return arg;
}
// Nr will be of type number by the compiler.
let nr = test(12);
您应该阅读有关打字稿中的泛型以及一般情况。 – toskv
一个是类型断言,另一个是函数返回类型。我看不出他们如何进行比较。 – Saravana