react中useParams传递泛型报错:不能将类型“你定义的接口”分配给类型“Record<string, string | undefined>”,类型“接口”中缺少类型索引

当我们用interface定义的MatchParams接口传给useParams时会出现下面错误提示:

类型“MatchParams”不满足约束“string | Record<string, string | undefined>”。
不能将类型“MatchParams”分配给类型“Record<string, string | undefined>”。
类型“MatchParams”中缺少类型“string”的索引签名。

解决方法(对应代码示例在下方):

  1. 我们可以把用interface定义的接口改成用type定义
  2. 我们可以在interface的接口中加入缺少的索引, 我的demo中是缺少string索引,所以给interface中加上对应的索引就可以

导致这个错误的原因:

我们可以看到下面useParams的定义, 其泛型ParamsOrKey继承了一个联合类型
,而interface只能定义一个对象类型不能用于定义联合类型的泛型,typescript后面类型别名开始支持泛型,所以可以用type来定义。
export declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[
ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;

以上个人理解, 希望各位大佬指正

interface和 type 适用场景: 
1. interface: 
    对象类型定义
    同名接口属性合并 适用interface接口
2. type:
	  定义基本类型的别名时,
	  定义元组类型时,
	  定义函数类型时,
	  定义联合类型时,
	  定义映射类型时,使用 type 
import { useParams } from 'react-router-dom';
import React from 'react';

interface Param {
	[key: string] : string;
}
interface MatchParams {
    id: string;
}
interface MatchParamsRight extends Param {
    id1: string;
}
type MatchType = {
    i: string;
};
const Test: React.FC = (props) => {
    const { id = '1' } = useParams<MatchParams>(); // 会报错
    const { id1 = '1'} = useParams<MatchParamsRight>(); // interface 解决报错
    const { i = '1' } = useParams<MatchType>();
    return <></>;
};

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值