TS
typescript是拥有类型的javaScript超集, 它可以编译成普通\干净\完整的js代码 ES3
js所拥有的内容ts都支持, 并且js有ES67... ts也都支持这些语法.
1.ts全局安装typescript
npm install -g typescript
tsc 文件名.ts
node 文件名.js
2.数据类型 <1>number
let num:number=123
let decLiteral: number = 6;
let binaryLiteral: number = 0b1010;
let hexLiteral: number = 0xf00d;
let octalLiteral: number = 0o744;
<2>boolean
let flag: boolean = true;
flag = false;
<3>string
let name:string="小爱"
let msg:string="hello"
msg = `${name}`
<4>null和undefined
let u: undefined = undefined;
let n: null = null;
<5>symbol
let name:symbol=Symbol("name")
let name1:symbol=Symbol("name")
const obj = {
[name]: "hello",
[name1]: "你好",
}
<6>void
function fn(num:number, num1:number): void{
console.log(num+num1)
}
let sum = fn(5,3)
<7>never
function fn(): never{
throw new Error("手动错误")
}
fn()
<8>any
let num:any="123"
num = 123;
num = null;
2.TS中的类型 <1>联合类型
let num:number|string=123
num="123"
<2>交叉类型
let b=number&string
<3>可选类型
function fn(msg?:string){
console.log(msg)
}
fn();
fn(undefined);
fn("hello world")
3.TS中的类 <1>ts中类的成员修饰符
class Person{
public name!:string;
public age:number;
constructor(name:string, age:number) {
this.name = name;
this.age = age;
}
running(){
console.log(this.name + " running")
}
eating(){
console.log(this.name + " eating")
}
}
class Student extends Person{
public learn: string;
constructor(name:string, age:number, learn: string) {
super(name, age);
this.learn = learn
}
running(){
super.running()
console.log(this.name + " Student running")
}
}
let s: Student = new Student("学生", 20, "TypeScript");
s.running();
s.eating();
console.log(s)
class Person{
private name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa");
class Person{
protected name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa");
class Person{
readonly name:string;
constructor(name:string) {
this.name = name;
}
}
let p = new Person("aa");
4.TS中的接口interface <1>接口声明
interface Person{
name:string,
age:number
}
let obj:Person={
name:"haha",
age: 18
}
<2>interface的继承
interface Obj {
name: string,
run: () => void
}
interface Obj2 {
age: number
}
interface Obj3 extends Obj, Obj2 {
jump: () => void
}
let obj: Obj3 = {
name: "你好",
age: 18,
run(){},
jump(){}
}
<3>interface和type的区别
interface Person {
name: string,
run:()=>void
}
interface Person {
age: number
}
let obj: Person = {
name: "aa",
run(){},
age: 18
}
<4>interface字面量赋值
interface Person{
name: string,
age: number
}
let obj = {
name: "你好",
age: 18,
flag: true
}
let p:Person = obj;
5.TS的泛型
function fn<T=string>(arg:T):T{
console.log(arg)
return arg
}
fn<string>("1234")
fn<number>(123)
fn<number[]>([1,2,3])
|