Good day
Trying to deal with generics
There are 2 types
TUserInfo
type TUserInfo = {
id: num,
readonly fname: string,
readonly lname: string
}
TBody
type TBody = {
success: boolean,
user?: any
}
Tell me how to pass any type to TBody
(for example, TUserInfo
). And user
should have the same type instead of any
.
Thank you in advance
CodePudding user response:
I think it is better to use discriminated unions in this case:
export interface User {
id: number,
fname: string,
lname: string
}
type Response<T> =
| {
success: true;
user: T
}
| {
success: false
}
type Result = Response<User>
declare var result: Result
if (result.success) {
result.user
} else {
result.success // false
result.user // error
}
I'd willing to bet that if success
if false
- user
property should be ubdefined
.
Result
type is pretty popular monad.
See Rust Result, F# Result
CodePudding user response:
In typescript, you can create interfaces.
export interface TUserInfo {
id: number,
fname: string,
lname: string
}
export interface TBody {
success: boolean,
user?: TUserInfo
}
CodePudding user response:
Did so
type TBody<T> = {
success: boolean;
user?: T;
}