Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object values type recognition using generic

I need to detect the function’s param type (it’s using the described type) and build the same object type according to the described type (recognize provided fields and get value types using the described one).

Typing:

// the describe type
type StorageData = {
  prop1: boolean;
  prop2: number;
  prop3: string;
  prop4: "static" | "dynamic";
};

type ParamsToGet = Partial<StorageData>;

type Callback<T> = (data: T) => void;

type Get = <T extends ParamsToGet>(params: T, callback: Callback<T>) => void;

declare const get: Get;

Using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

get({ prop1: false, prop4: "static", prop2: 1}, (data) => { ... });

/*
Current typing:

data: {
    snowfallColor: string;  // ok
    snowfallZtop: true;     // wtf? should be boolean
    snowfallCount: number;  // ok
}
*/

The problem is that all property value types are detecting correctly, instead of bools, in this case, I’m getting true or false instead of boolean.

>Solution :

Instead of having the generic type extend StorageData, which allows typescript to get more specific, you could instead have it extend keyof StorageData, which gives you Partial-like functionality but lets you retain the original types:

type Get = <K extends keyof StorageData, T = Pick<StorageData, K>>(params: T, callback: Callback<T>) => void;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading