常用知识
- 如果想恢复JS的灵活性,可以将数据类型定义为any
- 联合类型 string|number
- 也可以这样声明 (下面的声明方式叫做”别名”)
type BoolAndNumber = true | false | Number
- 也可以这样声明 (下面的声明方式叫做”别名”)
- 接口
interface Man {readonly name: string; //设置为只读属性age?: number; //?表示这个是可选属性[x: string]: any; //这行用来设置一些{0,无穷}不存在的属性}let a: Man = {name: "a",age: 18,work: "student",go: "ww",};let b: Man = {name: "b",age: 99,email: "xxxx@xxx.com",};

```tsx //可选参数以及参数默认值 function Print(str:string,age:number=18,str2?:string){ if(str2){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)
}else{console.log(str+` ${age} `+str2)
} }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;
