TypeScript类型系统与面向对象编程深度解析
1. TypeScript类型系统基础
TypeScript的类型系统提供了强大的类型推断功能,能帮助开发者在编写代码时减少类型注解的使用。
1.1 类型推断
类型推断是TypeScript的核心特性之一,它允许编译器根据上下文自动推断变量的类型。
- 自下而上和自上而下的推断 :在函数中,返回值可以用来确定函数的返回类型。例如:
function add(a: number, b: number) {
/* The return value is used to determine
the return type of the function */
return a + b;
}
在匿名函数中,参数类型也可以根据上下文推断。如下面的代码:
interface CallsFunction {
(cb: (result: string) => any): void;
}
// The cb parameter is inferred to be a function accepting a string
var callsFunction: CallsFunction = function (cb) {
cb('Done');
// Error: Argument of
TypeScript类型与OOP深度解析
超级会员免费看
订阅专栏 解锁全文
7

被折叠的 条评论
为什么被折叠?



