The following code has OfficeDocument type which was inferenced from User, but userId should be number without undefined. Required doesn't work.
How can I do it? I'd like for example to get an error in calling the handleDocument function about incorrect type.
type User = {
id: number | undefined;
}
type OfficeDocument = {
userId: Required<User['id']>;
}
const handleDocument = (document: Required<OfficeDocument>) => {
console.log(document);
}
const user: User = {id: 10};
const officeDocument: OfficeDocument = {userId: undefined};
handleDocument(officeDocument);
CodePudding user response:
Required transforms an object type with optional properties into one with required properties. For example:
type User = {
id?: number;
}
type PopulatedUser = Required<User>;
// result:
// { id: number }
Using Required on something that isn't an object won't do anything. If you want to exclude undefined from a union, use NonNullable.
type OfficeDocument = {
userId: NonNullable<User['id']>;
}
CodePudding user response:
You can fix it by making id optional:
type User = {
id?: number
};
type OfficeDocument = {
userId: Required<User>['id']
};
const handleDocument = (document: OfficeDocument) => {
console.log(document);
}
const user: User = {id: 10}; // Works
const officeDocument: OfficeDocument = {userId: undefined}; // Error: Type 'undefined' is not assignable to type 'number'
handleDocument(officeDocument);
Then, the Required<> removes the optional, and forces OfficeDocument.userId to be a number. Also note the Required<User>['id'] instead of Required<User['id']>.
