PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] Why TypeScript cannot check property declare if all property optional?

 October 14, 2022     axios, typescript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing