'typescript construct to handle optional object type
I have a typescript function, findUser that I would like to have as inputs either a username (as a string) or a user_id as a number.
function findUser(info: { user_id: number } | { username: string}) {
if (info.user_id) {
}
if (info.username) {
}
}
I'm getting the typescript error on the info.user_id clearly because the user_id field it is not guaranteed to exist on info.
I realize an alternative way to do this is to define the function as
function findUser(info: { user_id?: number; username?: string}) {
and then it works, however clearly you can pass in an empty object and it would be nice to have a way to check against this.
(Also, I have a more-complicated structure with 4 types of inputs. And I think if I solve this simpler example, I can determine the more complicated one.)
My question: is there a way in typescript to do something like the first function definition?
Solution 1:[1]
You need to define both alternatives as type:
type UserInfo = { user_id: number; username?: string; } | { user_id?: number; username: string };
function findUser(info: UserInfo ) {
Note that this way will allow providing both user_id and username. If this is not desired, you can use never type:
type UserInfo = { user_id: number; username?: never; } | { user_id?: never; username: string };
function findUser(info: UserInfo ) {
Solution 2:[2]
I would do it that way
interface PropsName {
userName: string
userId?: string
}
interface PropsID {
userId: string
userName?: string
}
function findUser(info: PropsName | PropsID) {
if (info.userId) {
}
if (info.userName) {
}
}
Solution 3:[3]
you can use interfaces or a fast way like this
const findUser: { (name: string) : void; (Id: number): void; } = (value: string | number): void => {
if (typeof value === typeof 'string') { console.log("find by name") }
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 | Elias Soares |
| Solution 2 | Yoel |
| Solution 3 | DVG |
