5分钟上手TypeScript
文章目录
1.全局安装ts
npm install -g typescript
2.构建ts文件,编译成js
function greeter(person) {
return "Hello, " + person;
}
let user = "Jane User";
document.body.innerHTML = greeter(user);
tsc greeter.ts
3.基本概念-类型注解
// TypeScript里的类型注解是一种轻量级的为函数或变量添加约束的方式。
// TypeScript提供了静态的代码分析,它可以分析代码结构和提供的类型注解。
// 如果类型错误,会编译报错,并指出报错的位置;
function greeter(person: string) {
return "Hello, " + person;
}
let user = [0, 1, 2];
document.body.innerHTML = greeter(user);
4.基本概念-接口
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Jane", lastName: "User" };
document.body.innerHTML = greeter(user);
5.基本概念-类
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
6.手册指南-基础类型
布尔值
let isMarried: boolean = false;
数字
let age: number = 18;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
字符串
let name: string = "qinghuo";
let name: string = `qinghuo`;// 可以使用模板字符串
数组
let list: number[] = [1,2,3];
let list: string[] = ['a','b','c'];
let list: Array<number> = [1,2,3];
let list: Array<string> = ['a','b','c'];
元组
let list: [string,number];
list = ['a',1];//OK
list = [1,'a'];//error
// 当访问已知索引的元素的时候,会严格要求所属类型
console.log(list[0].substr(1)); // OK
console.log(list[1].substr(1)); // Error, 'number' does not have 'substr'
// 当访问越界元素的时候,会使用联合类型(string|number)任意其一
list[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型
console.log(list[5].toString()); // OK, 'string' 和 'number' 都有 toString;
list[6] = true; // Error, 布尔不是(string | number)类型
枚举
// 枚举元素编号默认是从0开始的,但是可以手动修改
enum Color {red,green=3,blue}
let color: Color = Color.green;
let colorName: string = Color[4];
console.log(colorName);// 'blue',因为green编号被赋值为3,所以blue的编号就是4
Any
// any类型是十分有用,它允许你在编译时可选择地包含或移除类型检查。
let notSure: any = 4;
notSure = "qinghuo";//OK
Void
// 函数没有返回值时,常见void
function warnUser(): void {
console.log("This is my warning message");
}
// 声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined或null;
let unusable: void = undefined;
let unusable: void = null;
Null和Undefined
let u: undefined = undefined;
let n: null = null;
Never
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为never
function fail() {
return error("Something failed");
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) { }
}
Object
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
类型断言
as
// 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用
let name: any = "qinghuo";
// 尖括号方式
let length: number = (<string>name).length;
// as方式
let length: number = (name as string).length;
7.手册指南-变量声明
let
块作用域
// 块作用域变量在包含它们的块或`for`循环之外是不能访问的
function f(input: boolean) {
let a = 100;
if (input) {
// Still okay to reference 'a'
let b = a + 1;
return b;
}
// Error: 'b' doesn't exist here
return b;
}
// 拥有块级作用域的变量的另一个特点是,它们不能在被声明之前读或写
a++; // illegal to use 'a' before it's declared;
let a;
重定义及屏蔽
let x = 10;
let x = 20; // 错误,不能在1个作用域里多次声明x
const
与let声明相似,但是就像它的名字所表达的,它们被赋值后不能再改变。 换句话说,它们拥有与let相同的作用域规则,但是不能对它们重新赋值。
const numLivesForCat = 9;
const kitty = {
name: "Aurora", numLives: numLivesForCat,
}
// Error
kitty = {
name: "Danielle", numLives: numLivesForCat
};
// all "okay"
kitty.name = "Rory";
kitty.name = "Kitty";
kitty.name = "Cat";
kitty.numLives--;
解构数组
let input = [1, 2];
let [first, second] = input;
console.log(first); // 1
console.log(second); // 2
// 使用扩展运算符...
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [ 2, 3, 4 ]
解构对象
let obj = {
name: 'qinghuo',
age: 18,
height: 175
}
let {name,age} = obj;
console.log(name);//'qinghuo'
console.log(age);//18
//使用扩展运算符...
let obj = {
name: 'qinghuo',
age: 18,
height: 175
}
let {name,...other} = obj;
console.log(name);// 'qinghuo'
console.log(other);// {age:18,height:175}
属性重命名
let obj = {
name: 'qinghuo',
age: 18,
height:175
};
let {name:a,age:b} = obj;
console.log(a);// 'qinghuo'
console.log(b);// 18
属性指定类型
let obj = {
name: 'qinghuo',
age: 18,
height:175
};
let {name,age}:{name:string,age:number} = obj;
属性添加默认值
let obj = {
name: 'qinghuo',
age: 18,
height:175
};
let {name,other=20} = obj;
console.log(name);//qinghuo
console.log(other);//20
函数声明
type C = { a: string, b?: number }
function f({ a, b }: C): void {
// ...
}
扩展运算符
...
// 数组使用扩展运算符...
let a = [1,2];
let b = [3,4];
let c = [0,...a,...b,5];
console.log(c);// [0,1,2,3,4,5]
//对象使用扩展运算符...
let a = {name:'qinghuo'};
let b = {age:18};
let c = {...a,...b};
console.log(c);// {name:'qinghuo',age:18}
8.手册指南-接口interface
必需属性
interface Jiekou {
name: string;
}
// 要求这个对象参数有一个名为name的参数,并且是string属性
function infos(obj:Jiekou){
console.log(obj.name);
}
infos({name:'qinghuo',age:18});
可选属性(属性后添加
?)
可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = {color: "white", area: 100};
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
只读属性(属性前添加
readonly)
interface People {
readonly name: string;
readonly age: number;
}
let a: People = { name: 'qinghuo', age: 18 };
a.age = 20; // error!
只读数组
ReadonlyArray<T>
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
// 把整个ReadonlyArray赋值到一个普通数组也是不可以的,但是可以用类型断言重写:
a = ro as number[];
readonlyvsconst
最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用const,若做为属性则使用readonly。
额外的属性检查
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
//...
}
// error: 'colour' not expected in type 'SquareConfig'`
let mySquare = createSquare({ colour: "red", width: 100 });
// 可以使用类型断言,绕开这些检查
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
// 最佳方式是,添加一个字符串索引签名
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
// 最后一种跳过这些检查的方式,就是将这个对象赋值给一个另一个变量: 因为`squareOptions`不会经过额外属性检查,所以编译器不会报错。
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
let result = src.search(sub);
return result > -1;
}
可索引的类型
定义了StringArr接口,它具有索引签名。
这个索引签名表示了当用number去索引StringArr时会得到string类型的返回值。
interface StringArr {
[index: number]: string;
}
let arr: StringArr;
arr = ["qinghuo", "五星大饭店"];
let str: string = arr[0];
console.log(str);//'qinghuo'
TypeScript支持两种索引签名:字符串和数字。 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用number来索引时,JavaScript会将它转换成string然后再去索引对象。 也就是说用100(一个number)去索引等同于使用"100"(一个string)去索引,因此两者需要保持一致。
class Animal {
name: string;
}
class Dog extends Animal {
breed: string;
}
// 错误:使用数值型的字符串索引,有时会得到完全不同的Animal!
interface NotOkay {
[x: number]: Animal;
[x: string]: Dog;
}
name的类型与字符串索引类型不匹配,所以类型检查器给出一个错误提示:
interface NumberDictionary {
[index: string]: number;
length: number; // 可以,length是number类型
name: string // 错误,`name`的类型与索引类型返回值的类型不匹配
}
可以将索引签名设置为只读,这样就防止了给索引赋值:
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let arr: ReadonlyStringArray = ["qinghuo", "五星大饭店"];
arr[2] = "abc"; // error!
类类型
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
类静态部分与实例部分的区别
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
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);
继承接口
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
混合类型
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
接口继承类
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
select() { }
}
class Location {
}
在上面的例子里,SelectableControl包含了Control的所有成员,包括私有成员state。 因为state是私有成员,所以只能够是Control的子类们才能实现SelectableControl接口。 因为只有Control的子类才能够拥有一个声明于Control的私有成员state,这对私有成员的兼容性是必需的。
在Control类内部,是允许通过SelectableControl的实例来访问私有成员state的。 实际上,SelectableControl接口和拥有select方法的Control类是一样的。Button和TextBox类是SelectableControl的子类(因为它们都继承自Control并有select方法),但Image和Location类并不是这样的。
9.手册指南-类
10.手册指南-函数
11.手册指南-泛型
12.手册指南-枚举
13.手册指南-类型推论
14.手册指南-类型兼容性
15.手册指南-高级类型
16.手册指南-Symbols
17.手册指南-迭代器和生成器
18.手册指南-模块
19.手册指南-命名空间
20.手册指南-命名空间和模块
21.手册指南-模块解析
22.手册指南-声明合并
23.手册指南-JSX
基本介绍
- 给文件一个
.tsx扩展名 - 启用
jsx选项
TypeScript具有三种JSX模式:preserve,react和react-native。 这些模式只在代码生成阶段起作用 - 类型检查并不受影响。
| 模式 | 输入 | 输出 | 输出文件扩展名 |
|---|---|---|---|
| preserve | <div /> | <div /> | .jsx |
| react | <div /> | React.createElement("div") | .js |
| react-native | <div /> | <div /> | .js |
as操作符
var foo = <foo>bar;
//由于不能够在.tsx文件里使用上述语法,因此我们应该使用另一个类型断言操作符:as
var foo = bar as foo;
类型检查
为了理解JSX的类型检查,你必须首先理解固有元素与基于值的元素之间的区别。
- 对于React,固有元素会生成字符串(
React.createElement("div")),然而由你自定义的组件却不会生成(React.createElement(MyComponent))。- 传入JSX元素里的属性类型的查找方式不同。 固有元素属性_本身_就支持,然而自定义的组件会自己去指定它们具有哪个属性。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论