博客 / 詳情

返回

TS泛型粗淺理解 一

在使用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類型的 111
test<string | boolean>('hahaha')//返回值是string類型的 hahaha
test<string | boolean>(true);//返回值是布爾類型的 true

參考文章

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.