常用知识

  • 如果想恢复JS的灵活性,可以将数据类型定义为any
  • 联合类型 string|number
    • 也可以这样声明 (下面的声明方式叫做”别名”)type BoolAndNumber = true | false | Number
  • 接口
    1. interface Man {
    2. readonly name: string; //设置为只读属性
    3. age?: number; //?表示这个是可选属性
    4. [x: string]: any; //这行用来设置一些{0,无穷}不存在的属性
    5. }
    6. let a: Man = {
    7. name: "a",
    8. age: 18,
    9. work: "student",
    10. go: "ww",
    11. };
    12. let b: Man = {
    13. name: "b",
    14. age: 99,
    15. email: "xxxx@xxx.com",
    16. };
    Typescript - 图1
    let arr:number[]=[1,2,3,4]
    let arr1:Array<number>=[5,10,15]
    arr.push(11)
    console.log(arr,arr1)
    arr.pop()
    console.log(arr)
    
    ```tsx //可选参数以及参数默认值 function Print(str:string,age:number=18,str2?:string){ if(str2){
      console.log(str+` ${age} `+str2)
    
    }else{
      console.log(str+` ${age} `)
    
    } }

Print(“aaa”) Print(“bbb”,1) Print(“bbb”,1,”ccc”)

```tsx
let person:[string,number]=['aaa',18]
console.log(person)
//单独赋值
let a=[]
a[0]=1
a[1]='aaa'
console.log(a)
//一次赋值时必须同时赋两个值
a=[12,'bbb']
console.log(a)

类与接口

interface Do{
    sleep(h:number):string
}

class Person implements Do{
    name:string
    constructor(name:string) {
        this.name=name
    }

    say(sth:string):string{
        return `My name is ${this.name},and ${sth}`
    }

    sleep(h:number):string{
        return `睡了${h}小时`
    }
}

let a:Person=new Person("aaa")
console.log(a.say("I'm Unhappy!"))
console.log(a.sleep(10))

不要使用非空断言

//✅    
if (!a.current) return;
    a.current.focus();

//❌
a.current!.focus()

使用ref时的ts类型

import { useRef } from "react";
function App() {
  const a = useRef<HTMLInputElement>(null);
  const handleClick = function () {
    if (!a.current) return;
    a.current.focus();
  };
  return (
    <div className="App">
      mirrorhooks
      <button onClick={handleClick}>聚焦</button>
      <input ref={a} />
    </div>
  );
}
export default App;

入门Typescript(从英文的官方文档入手)