TS基础02
函数
我们没必要明确声明 circle 是一个函数,TypeScript 会进行类型推断。TypeScript 还会推断函数的返回类型,但是如果函数体比较复杂,还是建议清晰的显式声明返回类型。
const circle = (diam: number): string => { return '圆的周长为:' + Math.PI * diam; }; //我们可以在参数后添加一个?,表示它为可选参数;另外参数的类型也可以是一个联合类型: const add = (a: number, b: number, c?: number | string) => { console.log(c); return a + b; }; console.log(add(5, 4, '可以是 number、string,也可以为空'));
any基本上可以将 TypeScript 恢复为 JavaScript
我们还可以用函数的类型签名声明一个函数属性,通用函数(sayHi)和箭头函数(sayBye)都可以声明:
interface Animal{ eat(name:string):string; speaak:(name:string)=>string; } let tom:Animal={ eat:function(name:string){ return `eat${name}` },```speaak:(name:string)=>`speak ${name}` } // let a=tom.eat('zeze') // let b=tom.speaak('hh') console.log(tom.eat('zeze'),tom.speaak('hh'))
Dom和类型转换
ts没办法像js那样访问dom,这就意味着ts没办法确定这些dom是否存在,所以使用非空断言,我们可以明确的告诉编译器这个表达式是否是null/undefined, ts可以通过类型推断确认它的类型为 HTMLAnchorElement。
非空断言 x! 将从 x 值域中排除 null 和 undefined.
const link = document.querySelector('a')! console.log(link) //null //如果我们需要通过 class 或 id 来选择一个 DOM 元素时,通过类型转化来实告知ts,该元素存在且知道他的类型时 HTMLFormElement const from = document.getElementById('form') as HTMLAnchorElement console.log(from)
类
可以定义类中的每条数据的类型
class Person{ name:string; iscool:boolean; age:number; constructor(n:string,c:boolean,a:number){ this.name=n this.iscool=c this.age=a } sayHi(){ return `Hi,woshi ${this.name},jinnian ${this.age}` } } const person3=new Person('haha',true,18) console.log(person3.sayHi())
创建一个仅包含person类的数组对象
let people:Person[]=[person3] console.log(people)
类的修饰符readonly,private,protected,public
class Pobj{ readonly name:string; //不可以更改 private iscool:boolean; //pobj类的私有属性,外部访问不到 protected email:string; //只能从这个类和他的子类中进行访问和修改 public age:number; constructor(n:string,c:boolean,e:string,a:number){ this.iscool=c this.name = n this.age = a this.email=e } sayHi(){ return `Hi,woshi ${this.name},jinnian ${this.age}` } } const p1 = new Pobj('ConardLi', true, 'conard@xx.com', 17); console.log(p1); // ConardLi // p1.name = 'Jerry';
我们可以通过下面的写法,属性会在构造函数中自动分配,我们类会更加简洁:
class Pobje{ constructor( readonly name:string, //不可以更改 private iscool:boolean, //pobj类的私有属性,外部访问不到 protected email:string, //只能从这个类和他的子类中进行访问和修改 public age:number, ){} sayHi(){ return `Hi,woshi ${this.name},jinnian ${this.age}` } }
评论(0)
暂无评论