Reputation: 38
Typescript has Required<T>
utility type which constructs type consisting of all properties of T set to required. But I want to make only specific properties as required, not all. So I've written my own template(sorry about my C++ lexicon) to do it.
interface MyProps {
foo1?: number;
foo2?: number;
}
type RequiredProperties<T, RequiredProps extends keyof T> = Required<Pick<T, RequiredProps>> &
Omit<T, RequiredProps>;
// remove "optional" modifier from the next properties
type requiredProps = 'foo1';
type MakeFoo1Required<T> = RequiredProperties<T, requiredProps>; // <-- got error here
type NewMyProps1 = RequiredProperties<MyProps, requiredProps>; // <-- yes, it works fine
type NewMyProps2 = MakeFoo1Required<MyProps>; // <-- but I wanna to create it through the alias
It works fine, but I got a tsc error
Type '"foo1"' does not satisfy the constraint 'keyof T'.
It happens because tsc does not know that "foo1" is a keyof T.
So I wonder is there a way to solve it?
Upvotes: 0
Views: 96
Reputation: 37948
You can add constraint requiring T
to have requiredProps
:
type MakeFoo1Required<T extends { [K in requiredProps]?: any }> = RequiredProperties<T, requiredProps>;
Upvotes: 1