JavaScript超集
注意:TypeScript无法在浏览器中运行
let count: number = 2
let name: string = 'genggeng'
let flag: string = true
let list1:number [] = [1,2,3,4] //数字类型的数组
let list2:Array<number> = [1,2,3,4] //数字类型的数组
let list3 = [1,2,3,4]
let list4 = [1,'aa',true]
let list5 :any[] = [1,'aa',3,4]
let person1 : [number,string] = [1,'哈哈哈']
// person1[1] = true; //报错
// person1[0] = 'sww' //报错
// person1[1] = true; //报错
let merge: number | string | string[];
let union: 1 | '2' | true;
enum Color {
red = 2,
green = 'green',
blue = 5,
}
let color1 =Color.green
console.log(color1);
// any 适合代码的快速成型
let value: any = 666;
value = true;
value = 1;
value = '哈哈哈';
value = {};
value = [];
value()
// 代码类型更安全
let value: unknown = 666;
value = true;
value = 1;
value = '哈哈哈';
value = {};
value = [];
value() //报错
void:变量不存在
underfined:变量没有赋值,没有初始化
never:函数永远执行不完 ------------ 实际开发中用来处理异常
function printResult(): void {
console.log('嘿嘿嘿');
}
console.log(printResult()); // undefined
function printResult1(): undefined {
console.log('哈哈哈');
return
}
console.log(printResult1()); // undefined
function throwError(mes: string, code: number): never {
throw {
mes,
code,
};
}
throwError('not found', 404);
console.log('这句代码永远执行不到')
let message: any ;
message = 'abc' // 不会改变初始类型
// message.endWith('ee') //报错
let ddd =(<string>message).endsWith('a')
let ddd2 =(message as string).endsWith('c')
console.log(ddd); // false
console.log(ddd2); // true
let fn1 =(params:number,params2=0,params3?:string)=>{
console.log(params);
console.log(params2);
console.log(params3); // ? 标识可选 只能从最后开始往前设置
}
// fn1() 报错
fn1(1)
fn1(1,3,'33')
const person ={
name:'gg',
id:111,
age:18
}
console.log(person.name);
let drawPoint = (point: Point) => {
console.log({ x: point.x, y: point.y });
};
drawPoint({ x: 1, y: 2 });
// drawPoint({x:'1',y:'2'}); //报错
// drawPoint({xw:'1',yt:'2'}); //报错
interface Point {
x: number;
y: number;
}
interface IPoint {
x: number;
y: number;
drawPoint: () => void;
getDistance: () => number;
}
class Point implements IPoint {
constructor(public _x: number, public _y: number) {}
drawPoint = () => {
console.log('x:', this.x, 'y:', this.y);
};
getDistances = (p: IPoint) => {
return Math.pow(p.x - this.x, 2) + Math.pow(p.y - this.y, 2);
};
}
与 js 类似
export 导出
import from 导入
类型<>
let lastInArray =<T=number>(arr: T[])=>f //泛型默认number
return arr[arr.length - 1];
}
const l1 = lastInArray( [1,2,3,4]);
const l2 = lastInArray( ["a","b","c"]);