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?
CodePudding user response:
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 ) {
CodePudding user response:
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) {
}
}
CodePudding user response:
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") }