1.变量
var [变量名] : [类型] = 值;
const hello:string = "hello world";
console.log(hello);
如果值不是指定类型会报错!
2.模块
一个文件就是一个模块,模块可以导出供其它模块,也可以导入其它模块来使用
// 文件名 a.ts
export class Person {
name:string;
constructor(name:string){
this.name = name;
}
sayhi():void {
console.log(this.name)
}
}
//文件名 b.js
import mod = require('./module');
const mods = new mod.Person("Jack");
mods.sayhi(); //Jack
3.函数
const 函数名 = (参数:类型):返回值类型=>{
return `hi ${name}`
}
//函数定义
const fun = (name:string):string=>{
return `hi ${name}`
}
const res = fun("jack");
console.log(res)
4.基础类型
同 js (布尔类型,数值类型,字符串类型,Null 与 Undefined 类型,)Any类型, ,Void类型,Never类型。
详细说明一下ts中新增类型
1.Any类型 ,可以被赋予任何类型的值;
let a:any = "Jack"
a = 1
a = false
2.Null 与 Undefined 类型, 它们是其他任何类型(包括 void)的子类型,可以赋值给其它类型。
- Null类型表示空值
- Undefined类型,表示未被赋值。
let a:null = null;
let b:string = '小明'
let c:undefined = undefined;
b=a;
b=c;
3.Void类型, 表示无类型
//void
// 申明为 void 类型的变量,只能赋予 undefined 和 null
let a:void = undefined;
a = null
//没有返回值的函数,其返回值类型为 void
function warnUser(): void {
console.log("This is my warning message");
}
warnUser()
4.Never类型: never类型表示的是那些永不存在的值的类型.
never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型
function error(message: string): never {
throw new Error(message);
}
5.never 和 void 的差异
void 表示没有任何类型,never 表示永远不存在的值的类型。
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
// 这个函数不能申明其返回值类型是 never
function warnUser(): void {
console.log("This is my warning message");
}