当我们用interface定义的MatchParams接口传给useParams时会出现下面错误提示:
类型“MatchParams”不满足约束“string | Record<string, string | undefined>”。
不能将类型“MatchParams”分配给类型“Record<string, string | undefined>”。
类型“MatchParams”中缺少类型“string”的索引签名。
解决方法(对应代码示例在下方):
- 我们可以把用interface定义的接口改成用type定义
- 我们可以在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 <></>;
};