'Typescript type inference without undefined
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);
Solution 1:[1]
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']>;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
