1.类型注解 :
为函数和变量添加约束的方式
function sayHello(name : string) {
return "Hello, " + name ;
}
let name = "shu xiaoxiao";
greeter(name);
//调用结果:Hello, shu xiaoxiao
2.接口 :
使用接口来描述一个拥有具体字段的对象,要求我们在实现接口时候包含了接口要求的结构
interface Gril{
firstName: string;
lastName: string;
}
function sayHello(girl: Gril) {
return "Hello, " + girl.firstName + " " + girl.lastName;
}
let myName= { firstName: "shu", lastName: "xiaoxiao" };
greeter(myName);
//调用结果:Hello, shu xiaoxiao
3.类
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);
Ts基础类型
布尔值
let isDone: boolean = false;
数字
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
字符串
let name: string = "bob";
还可以使用模版字符串,它可以定义多行文本和内嵌表达式。 这种字符串是被反引号包围( `
),并且以${ expr }
这种形式嵌入表达式
let name: string = `Gene`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ name }.
数组
第一种,可以在元素类型后面接上 []
,表示由此类型元素组成的一个数组:
let list: number[] = [1, 2, 3];
第二种方式是使用数组泛型,Array<元素类型>
:
let list: Array<number> = [1, 2, 3];
元组 Tuple
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error
当访问一个越界的元素,会使用联合类型替代:
x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型
枚举
enum
类型是对JavaScript标准数据类型的一个补充 使用枚举类型可以为一组数值赋予友好的名字。
???
Any
有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Void
某种程度上来说,void
类型像是与any
类型相反,它表示没有任何类型。 当一个函数没有返回值时,你通常会见到其返回值类型是 void
:
function warnUser(): void {
console.log("This is my warning message");
}
声明一个void
类型的变量没有什么大用,因为你只能为它赋予undefined
和null
:
let unusable: void = undefined;
Null 和 Undefined
TypeScript里,undefined
和null
两者各自有自己的类型分别叫做undefined
和null
。 和 void
相似,它们的本身的类型用处不是很大:
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
默认情况下null
和undefined
是所有类型的子类型。 就是说你可以把 null
和undefined
赋值给number
类型的变量。
Never
never
类型表示的是那些永不存在的值的类型。
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
Object
object
表示非原始类型,也就是除number
,string
,boolean
,symbol
,null
或undefined
之外的类型
类型断言
通过类型断言这种方式可以告诉编译器,“相信我,我知道自己在干什么”。 类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。
类型断言有两种形式。 其一是“尖括号”语法:
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;