Typescript核心
基本类型(Basic Types)
String
var name: string = 'Felipe';
Number
var age: number = 36;
Boolean
var married: boolean = false;
Array
var jobs: Array<string> = ['IBM', 'Microsoft', 'Google'];
var jobs: string[] = ['Apple', 'Dell', 'HP'];
var jobs: Array<number> = [1, 2, 3];
var jobs: number[] = [4, 5, 6];
元组(tuple)
let jobs: [string , number , string];
jobs = ['s1' , 12 , 's2']
Enums
enum Role {Employee, Manager, Admin};
var role: Role = Role.Employee;
Any
var something: any = 'as string';
something = 1;
something = [1, 2, 3];
Void
function setName(name: string): void {
this.name = name;
}
Null ,Undefined
let u: undefined = undefined;
let n: null = null;
Never
代表从来不会出现的值。
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
声明(Variable Declarations)
- 声明
var
,let
,const
,作用域类似ES6 - 解构赋值:数组解构,对象解构与ES6类似。
函数(Functions)
function buildName(firstName: string, lastName?: string):string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
let result3 = buildName(1, 2); // error
支持默认参数,可选参数,剩余参数,箭头函数等
类(Classes)
修饰符关键字public
,private
, protected
, static
,readonly
class Person {
static version = '1.0.0';
protected sexes = ['male' , 'female'];
first_name: string;
last_name: string;
age: number;
constructor(first_name: string, last_name: string, age: number) {
this.first_name = first_name;
this.last_name = last_name;
this.age = age;
}
greet() {
console.log("Hello", this.first_name);
}
ageInYears(years: number): number {
return this.age + years;
}
}
继承和抽象类(Abstract Classes)
abstract class Animal {
abstract makeSound(): void; //必须在派生类中实现
move(): void {
console.log("roaming the earth...");
}
}
//派生类
class Person extends Animal {
makeSound():void {
console.log("say sb");
}
}
接口(Interfaces)
属性接口
interface FullName {
firstName: string;
lastName?: string;
}
function logName(name: FullName) {
console.log(name.firstName , name.lastName);
}
函数类型接口
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
类类型接口
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}
泛型(Generic)
function identity1(arg: number): number {
return arg;
}
function identity2(string: string): string {
return arg;
}
// 放弃类型检查
function identity(arg: any): any {
return arg;
}
//使用泛型
function identity<T>(arg: T): T {
return arg;
}
// test ...
let output = identity<string>("myString");
// or
let output = identity<number>("myString");
模块(Modules)
与es6一样,使用export
和import
导出导入模块。
装饰器(Decorators)
Typescript提供的几种装饰器:
方法装饰器
@enumerable
decorator 的定义
function enumerable(value: boolean) {
return function (
// 类的原型对象
target: any,
// 方法的名字
propertyKey: string,
// 成员属性的描述
descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
@enumerable
decorator 的使用
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@enumerable(false)
greet() {
return "Hello, " + this.greeting;
}
}
类装饰器:
@Component装饰器
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
names: string[];
constructor() {
this.names = ['Ari', 'Carlos', 'Felipe', 'Nate'];
}
ngOnInit() {
console.log('com init hook')
}
}
参数装饰器:
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(@required name: string) {
return "Hello " + name + ", " + this.greeting;
}
}
属性装饰器:
class Greeter {
@format("Hello, %s")
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
let formatString = getFormat(this, "greeting");
return formatString.replace("%s", this.greeting);
}
}
装饰器组合:
@decorator1
@decorator2
class Person(){}
- ES2017 已经引入了这项功能,目前 Babel 转码器已经支持。
- Typescript提供的几种装饰器源码
其他
Symbols 、迭代器、命名空间(namespace)等
小结
参考
- https://github.com/Microsoft/TypeScript
- https://www.typescriptlang.org/docs/handbook/basic-types.html
- https://www.tslang.cn/docs/home.html
- https://github.com/Microsoft/TypeScript/blob/master/lib/lib.dom.d.ts
- http://definitelytyped.org/
- http://www.typescriptlang.org/play/index.html
反馈与建议
- 您可通过 该链接 查看所有的文章。
- 也可通过 GitHub issues 或通过 简书 评论这篇文章,希望能留下您宝贵的建议。
- 如有任何问题,您可以通过邮箱 @liguwe@qq.com 或微博 @August008 联系我。