我创建了一个再造产品:https://stackblitz.com/edit/vitejs-vite-wfqafu?file=src%2Fmain.ts
核心代码如下:
import Axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
interface Params {
page?: number;
limit?: number;
}
const req = (
opts: Omit<AxiosRequestConfig, 'params'> & {
params: Params;
}
) => Axios({ url: '/', ...opts });
const query = {
pag: 2,
limit: 10,
};
req({ params: query });
我认为query
不匹配Params
接口,因为pag
不再在Params
属性上,为什么typescript不检查上述代码中的错误?
如果我显示定义查询的类型,我可以得到正确的检查:
// Type '{ pag: number; limit: number; }' is not assignable to type 'Params'.
const query: Params = {
pag: 2,
limit: 10,
};
req({ params: query });
关于AxiosRequestConfig
define in this.
TypeScript没有提供严格类型匹配的内部方式或实用程序类型。下面是一些你可以用来实现的东西:
type StrictMatch<T, S> = T extends S
? Exclude<keyof T, keyof S> extends never
? T
: never
: never;
用法(代码简化为简洁):
interface Params {
page?: number;
limit?: number;
}
const req = <T>(opts: { params: StrictMatch<T, Params> }) => {};
const querySuccess = {
page: 2,
limit: 10,
};
const queryFails = {
pag: 2,
limit: 10,
};
req({ params: querySuccess }); // works flawlessly
req({ params: queryFails }); // Error: Type '{ pag: number; limit: number; }' is not assignable to type 'never'