Issue
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:
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;
Answered By - grimsteel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.