Except: Enhancing parameter types#1425
Conversation
There was a problem hiding this comment.
Copilot wasn't able to review any files in this pull request.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
I think this changes the contract too much.
I agree with fixing the generic conditional type case, but I don't think the fix should drop the strict key guarantee for normal object types. That guarantee is one of the main reasons this type exists, becuase otherwise it gets much closer to |
|
@Emiyaaaaa In cases like these, simply taking an intersection would silence the error: import type {Except} from "type-fest";
type GenericType<T> = T extends string ? {
foo: T;
bar: string;
} : {
baz: T;
};
type GenericTypeExcept<T> = Except<GenericType<T>, 'foo' & keyof GenericType<T>>; // ✅ Works
type G1 = GenericTypeExcept<string>;
//=> { bar: string; }
type G2 = GenericTypeExcept<number>;
//=> { baz: number; }This is better IMO because you're acknowledging that the second argument needs to be Moreover, in the above example, the compiler rightly complains because import type {Except} from "type-fest";
type GenericType<T> = T extends string ? {
foo: T;
bar: string;
} : {
foo: string; // <--- Added `foo` here too
bar: T;
};
type GenericTypeExcept<T> = Except<GenericType<T>, 'foo'>; // ✅ Works
type G1 = GenericTypeExcept<string>;
//=> { bar: string; }
type G2 = GenericTypeExcept<number>;
//=> { bar: number; } |
|
@sindresorhus @som-sm Let's see the simpler case: type A = { foo: string } | { bar: number };
type B = Except<A, 'foo'> // should throw error or not?Is the union type included in the design of |
@Uygniqoar You can use the |
|
@Emiyaaaaa Shall we close this then? |
Exceptnot playing well conditional types and/orinfer#1421When the 2nd input param
KeysTypeis clearly defined,keyof ObjectTypecan correctly constrain and suggest parameter options. However, when the input type is ambiguous due to generics,keyof ObjectTypeprevents the parameter from passing.LiteralUnioncan relax the strict input type, and still maintain the parameter suggestions.If there are ok, I can fix similar problems in other PRs.