在使用react-router-dom的时候,用到了useMatches的方法,ts一直提示报错,如下:
根据提示,找到了这个类型:
export interface UIMatch<Data = unknown, Handle = unknown> {
id: string;
pathname: string;
params: AgnosticRouteMatch["params"];
data: Data;
handle: Handle;
}
import type {UIMatch} from "react-router-dom"
这才对泛型有了一丢丢理解。 使用时的场景:
const location = useLocation()
let matches = useMatches();
useEffect(() => {
let match = matches.find((item: any) => item.pathname == location.pathname)
if(match) {
let arr = match?.handle?.breadcrumb.map((item: string) => {
return {
title: item
}
})
}
}, [location.pathname])
breadcrumb一直提示报错
发现matches的数据类型为UIMatch<unknown, unknown>所以报错
根据UIMatch的类型提示,我们发现Data和Handle的类型为unknown,所以这时候需要使用any进行强制类型转换, 代码如下:
let matches = useMatches() as any;
``
或者将matches的类型声明:
let matches:UIMatch<any, any>[] = useMatches()
注意的是:unknown只能接受any或者unknown类型。
接下来展示两个示例:
- 示例一
interface IParams<D = number, M = string> {
data: D,
m: M
}
function getPrams(path: IParams<number,string>):IParams<number, string> {
console.log(path)
return {
data: 2,
m: '3'
}
}
const params = getPrams({
data: 4,
m: '6'
})
- 示例二
function test <T> (arg:T):T{
console.log(arg);
return arg;
}
test<number>(111);// 返回值是number类型的 111
test<string | boolean>('hahaha')//返回值是string类型的 hahaha
test<string | boolean>(true);//返回值是布尔类型的 true