Hi,
Can someone help me understand why one of my types below works fine, but the other causes an error?
My understanding is these should be functionally the same, but I'm clearly missing something.
The error I receive on the broken one is:
Type 'keyof MyObject & string' cannot be used to index type '{ [K in keyof MyObject as K extends string ? K : never]: { column: K; op: "=" | "!=" | "<" | "<=" | ">" | ">="; value: MyObject[K]; }; }'
Both are filtering the keys of MyObject to just the string keys, but TS is moaning at me for one of them.
Any help understanding this would be great please.
export type WhereTypeWORKING<MyObject> = {
[K in Extract<keyof MyObject, string>]: {
column: K;
op: "=" | "!=" | "<" | "<=" | ">" | ">=";
value: MyObject[K];
};
}[Extract<keyof MyObject, string>];
export type WhereTypeBROKEN<MyObject> = {
[K in keyof MyObject as K extends string ? K : never]: {
column: K;
op: "=" | "!=" | "<" | "<=" | ">" | ">=";
value: MyObject[K];
};
}[keyof MyObject & string];
An example showing the same output from both methods of extracting string keys
type Table = {
id: number;
name: string;
42: boolean;
[Symbol.iterator]: () => Iterator<any>;
};
// both equate to "id" | "name"
type test = keyof Table & string
type test2 = Extract<keyof Table, string>
Many thanks in advance!