I just started using TypeScript in my Node projects and I was wondering if there is a cleaner, more concise way of implementing this:
import { XOR } from "ts-xor";
type _RemoveNull<T> = {
[P in keyof T] : string;
}
type UserIdParam = {
a: string;
}
type BudgetIdParam = UserIdParam & {
b: string | null;
}
type AccountIdParam = _RemoveNull<BudgetIdParam> & {
c: string | null;
}
type TransIdParam = _RemoveNull<AccountIdParam> & {
d: string | null;
}
type IdsParam = XOR<XOR<XOR<UserIdParam, BudgetIdParam>, AccountIdParam>, TransIdParam>;
I wanted a type that would accept any of these sample objects:
const a = {a: "1"};
const b = {a: "1", b: "2"};
const c = {a: "1", b: "2", c: "3"};
const d = {a: "1", b: "2", c: "3", d: "4"};
Also, only the last available property of the object can be null, that's why I had to intersect with the previous type and removed the null from the union.
I tried to do a union of the four types UserIdParam
, BudgetIdParam
, AccountIdParam
, and TransIdParam
but after I read other questions like this, I decided to use an XOR instead (ts-xor) to accomplish what I needed.
Please let me know your thoughts. Thanks!
--
EDIT: as mentioned by @Thomas in the comments, there is no concept of order for the object's properties, so there is no "last" one.