I have an interface and I want to create a type using the keys of this interface.
- The key can be optional
- The key must exist in that interface
For example:
interface Test {
a: string;
b: string;
c: string;
d: string | undefined;
e: string | undefined;
}
In my new type, only one property from the keys above should be allowed. This is how I defined it:
type MyNewType<T> = {
[key in keyof T]: T[key];
};
I used this type as MyNewType<Test>
, but encountered an error.
Type '{ a: string; }' is missing the following properties from type 'MyNewType': b, c, d, e.
How can I make these properties optional?
Explanation
I am utilizing a reducer in React and invoking the dispatch
function which takes an action creator as a parameter. The type Test
represents the state type and MyNewType<Test>
is the payload type. The action creator accepts different payloads such as { a: 'a'}
, { b: 'b' }
, or { d: undefined }
. However, I am getting an error indicating that the payload needs to include all properties.