在应用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的类型提醒,咱们发现DataHandle的类型为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类型的 111test<string | boolean>('hahaha')//返回值是string类型的 hahahatest<string | boolean>(true);//返回值是布尔类型的 true

参考文章