Issue
I have a type:
type SomeType = {
hello?: string | undefined;
world: number;
meow?: string;
};
I want it to become the following:
type SomeTypeExplicit = {
hello: string | undefined;
world: number;
meow: string;
};
By using this type, I want to enforce the “All optional properties should have the default value” rule in my components. Even if this default value if undefined
.
However, if I use Required<SomeType>
, I will get this, which is too strict:
type SomeTypeRequired = {
hello: string;
world: number;
meow: string;
};
If I use the elegant solution from “Required but possibly undefined type” question, I will get the following, which is too loose:
type SomeTypeLooseRequired = {
hello: string | undefined;
world: number;
meow: string | undefined;
};
How do I create such generic for SomeType
→ SomeTypeExplicit
transformation?
Solution
What you're looking for is the exactOptionalPropertyTypes
compiler option.
With exactOptionalPropertyTypes enabled, TypeScript applies stricter rules around how it handles properties on type or interfaces which have a ? prefix.
For example, you can't assign undefined
to a property marked as optional (?
) unless undefined
is assignbale to explicit type of the property.
type SomeType = {
hello?: string | undefined;
world: number;
meow?: string;
};
declare const someType: SomeType;
someType.meow = undefined; // error
someType.hello = undefined; // allowed
exactOptionalPropertyTypes
also affects how Required
maps an objects properties marked as optional. When set to true
unions that include undefined
are preserved.
type RequiredSomeType = Required<SomeType>
// type RequiredSomeType = {
// hello: string | undefined;
// world: number;
// meow: string;
// }
Answered By - Behemoth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.