Issue
I created a reproduct: https://stackblitz.com/edit/vitejs-vite-wfqafu?file=src%2Fmain.ts
The core code is as follows:
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 });
I think query does not match the Params interface because pag is not longer on the Params property, Why does typescript not check for errors in the above code?
If I display the type that defines the query, I can get the correct check:
// Type '{ pag: number; limit: number; }' is not assignable to type 'Params'.
const query: Params = {
pag: 2,
limit: 10,
};
req({ params: query });
About AxiosRequestConfig define in this.
Solution
TypeScript does not provide an internal way or utility type for strict type match. So here's something that you can use to make that happen:
type StrictMatch<T, S> = T extends S
? Exclude<keyof T, keyof S> extends never
? T
: never
: never;
Usage (code simplified for brevity) :
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'
Answered By - boop_the_snoot Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.