Issue
I want to know if there is a way I can create a generic type (something like NeverOptionals<T>) such that I can make all optional types on an interface never (kind of similar to Required<T> but not quite the same).
For example for the following interface:
interface Foo {
a?: string;
b: number;
c: string | undefined;
d?: number | undefined;
}
Using NeverOptionals<Foo> would be equivalent to the following interface:
interface FooNeverOptionals {
a?: never;
b: number;
c: string | undefined;
d?: never;
}
Solution
For your question, you can try the following codes. But { key?: never } will also be asserted to { key: undefined }, so I am not sure this is your want.
type NeverOptionals<T> = {
[P in keyof T]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : never;
}
If your purpose is to exclude the optional keys, you can try this.
interface Foo {
a?: string;
b: number;
c: string | undefined;
d?: string;
}
type NeverOptionals<T> = {
[P in keyof T]-?: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : never;
}
type ExcludeNever<T> = { [P in keyof T as T[P] extends never ? never : P]: T[P] };
type ExcludOptionals<T> = ExcludeNever<NeverOptionals<T>>
type T1 = ExcludOptionals<Foo>
// T1 = { b: number; c: string | undefined; }
Hope it can help you.
Answered By - Hsuan Lee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.