-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Description
Search Terms
require, require key, RequireProp, utility require, individual Required
Suggestion
Add a new RequiredProp utility type, which constructs a new type based on a passed interface, but requiring an specified property. It would be opposed to Omit utility type, and would use an approach similar to Required, but looking for an individual property. The implementation would be something like this:
type RequireProp<T, K extends keyof T> = T & { [P in K]-?: T[P] };
An alternative name could be RequireKey.
I was already preparing a PR, but as stated in the contributing guidelines, it is required for suggestions to be approved by a project maintainer first.
Use Cases
This would be useful in cases where the user can be confident about a property being set on an object. Functions that take a value and require a specific property to be set to work properly can benefit from this too.
I couldn't find a current approach for this other than self-declaring a similar utility type at project level, or creating a new interface that extends the "parent" one, requiring the necessary property.
Examples
interface Props {
a: number;
b?: number;
c?: number;
}
const obj: Props = { a: 5 }; // OK
const obj2: RequireProp<Props, 'b'> = { a: 5 }; // Error: property 'b' missing
const obj3: RequireProp<Props, 'b'> = { a: 5, b: 10 }; // OK
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code // If a type named "RequireProp" is already declared in the project,
tscwill prioritize the user-defined type over the library one - This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.