1、npm安装
npm install -g typescript
2、基础
类型注解
function greeter (person: string) {
return "hello,"+person;
}
//此类型为上面定义的string类型,否则会报错提醒,但是仍然执行
let userName = "唐启园"
document.body.innerHTML = greeter(userName);
接口
interface Person {
firstName: String;
lastName: String;
}
function greeter (person: Person) {
return "hello,"+ person.firstName + person.lastName;
}
let user = {
firstName:"唐园园",
lastName:"唐启园",
}
document.body.innerHTML = greeter(user)
类
class Person () {
fullName: string;
constructor( public firstName, public lastName) {
this.fullName = firstName + '---' + lastName;
}
}
interface People {
firstName: string;
lastName: string;
}
function greeter (people: People) {
return 'hello' + people.firstName + '---' + people.lastName;
}
let user = {
firstName: 'ty',
lastName:'唐园',
}
document.body.innerHTML = greeter(user)
3、基础类型
1.布尔值 (true/false)
let isDone: boolean = false;
2.数字
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;.//十六进制
3.字符串
let name: string = "bob";
name = "smith";
4.数组
let list: number[] = [1, 2, 3];
//使用数组泛型 Array<元素类型>
let list: Array<number> = [1, 2, 3];
5.元组Tuple
let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error
6.枚举
enum Color {Red, Green, Blue}//默认 0,1,2
let c: Color = Color.Green;
7.any 在编程阶段还不清楚类型的变量指定一个类型为any,类型检查器不对这些值进行检查而是直接让它们通过编译阶段的检查
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
8.void void类型像是与any类型相反,它表示没有任何类型
//该函数没有返回值,返回值的类型是void
function warnUser(): void {
console.log("This is my warning message");
}
9.null和undefined 和void相似,默认情况下null和undefined是所有类型的子类型
let u: undefined = undefined;
let n: null = null;
10.never 该类型表示的是那些永不存在的值的类型
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为never
function fail() {
return error("Something failed");
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
11.object object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型
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
12.类型断言 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。
//两种形式
// “尖括号”语法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
//'as'语法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
网友评论