带着浓浓windows风格的官网
入门教程1 入门教程2
本文给已熟练掌握js及es6,且有后端语言基于的开发者,快速上手
typescript是npm的一个标准包,安装即可用。编写的.ts文件需要编译
> npm install -g typescript
> tsc mycode.ts
变量,使用强类型
let isShow: boolean = false;
let count: number = 6; // 十六进制、二进制和八进制字面量,如 0xf00d、0b1010、0o744
let name: string = "bob";
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
let x: [string, number] = ['hello', 10]; // 越界的元素,会使用string | number替代
let notSure: any = 4; // 相当于没有规定类型
let unusable: void = undefined;
枚举enum
enum Color {Red = '红色', Green = '绿色', Blue = '蓝色'}
let c: Color = Color.Green; // 绿色
let colorEn: string = Color['绿色']; // Green
类型断言,类似强类型语言的(强制)类型转换
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
接口(interface),此接口非彼接口
这个概念很有js的一惯风格,就是诡异!![捂脸]
ts里的接口更像是其它强类型语言里的实体类,唉,你就不能叫个别的名
对值所具有的结构进行类型检查。
接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
作用于变量
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
printLabel({ size: 10, label: "sha sha sha" });
interface LabelledValue {
label?: string;
color?: string; // 可选,可以没有这个属性
}
function printLabel(labelledObj: LabelledValue) { ... }
printLabel({ label: "sha sha sha" });
interface LabelledValue {
readonly y: number; // 即 const
}
let myObj2: LabelledValue = { y: 14 };
myObj2.y = 0; // error readonly
下面,诡异的事情发生了,别眨眼
interface LabelledValue {
label?: string;
color?: string; // 可选,可以没有这个属性
}
function printLabel(labelledObj: LabelledValue) { ... }
printLabel({ size: 10, label: "sha sha sha" }); // error: 'size' not expected in type 'LabelledValue'
let temp = { size: 10, label: "sha sha sha" }
printLabel(temp) // ok [捂脸]
printLabel({ size: 10, label: "sha sha sha" } as LabelledValue)
也就是可选属性、多余属性不可共用,en...but,用变量中转一下就行了,或者强制转换一下就行了,或者设置索引签名(下面说)就行了
有点乱吗?我也乱
作用于方法
interface SearchFunc {
(source: string, subString: string): boolean;
}
// 不要求参数名一致,要求对应位置上的参数类型是兼容的
let mySearch: SearchFunc = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
索引签名
interface StringArray {
[index: number]: string;
}
let myArray: StringArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
表示了当用number去索引StringArray时会得到string类型的返回值。
// 错误:使用'string'索引,有时会得到Animal!
interface NotOkay {
[x: number]: Animal;
[x: string]: Dog;
}
interface NumberDictionary {
[index: string]: number;
length: number; // 可以,length是number类型
name: string // 错误,`name`的类型与索引类型返回值的类型不匹配
}
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];
myArray[2] = "Mallory"; // error!
类class
ts中的类,所有属性和方法默认为public。private(类外不可访问)、protected(实例不可访问)
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
class SubClass { constructor(msg: string) { super(msg); } }
class SubClass { constructor(protected msg: string) { super(msg); } } // 参数属性
有get、set拦截器的实体类
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (newName != "小明") {
this._fullName = newName;
}
else {
console.log("小明,你走开,我不要和你玩!");
}
}
}
静态属性、抽象类(abstract)...
实现接口
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface { // implements 实现接口内的属性
currentTime: Date; // 实现来的都是public
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
// ClockConstructor在这里是实体类检查,ctor需要是实现ClockInterface的、有两个参数的构造函数
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
// ClockInterface在这里是接口实现
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
// ClockInterface在这里是接口实现
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
类可以实现接口,接口可以继承(extends)接口,类可以继承(extends)类,类可以继承(extends)接口,接口可以继承(extends)类
模块扩展 declare
// 1.ts
export class AClass {
public a:string;
constructor(a:string) {
this.a = a;
}
}
// 2.ts
import { AClass } from './1';
declare module './1' {
interface AClass {
test: (b: number) => number;
}
}
AClass.prototype.test = (b: number): number => {
return b;
}
// 全局扩展
declare global {
interface String {
toJson: (str: string) => any;
}
}
String.prototype.toJson = (str: string):any => JSON.parse(str)
函数
ts方法入参:不可少传或多传
function buildName(firstName: string, lastName = "Smith") // 默认参数
function buildName(firstName: string, lastName?: string) // 可选参数
泛型 identity
嗯,好长啊,大概就是C#里的Dictionary<string, int>、List<string>
就这样吧