I was wondering if it is possible in typescript to type the max number of dynamic properties in an object.
So the basic example is for tracking events:
events.track('SOME_EVENT', { first: 'a', other: 'b', some: 'c'})
the event data is supposed to hold a maximum of 3 properties with their respective values, the keys could also be dynamic.
I've typed it with a basic Record
, but there is no limit on the amount of properties allowed:
export interface Events {
track: (name: string, params?: Record<string, string | number | unknown>) => void;
}
Is this possible?
CodePudding user response:
I can't think of a way to declare an object interface with 1-3 (but only 1-3) unknown string-named properties (but that doesn't mean there isn't one; I'm only at a journeyman level with TypeScript).
I'd lean toward a union of tuples:
type EventParam = [name: string, value: string | number | unknown];
type EventParams =
[EventParam]
| [EventParam, EventParam]
| [EventParam, EventParam, EventParam];
export interface Events {
track: (name: string, params?: EventParams) => void;
}
declare let events: Events;
// Works with 1:
events.track("something", [["first", "a"]]);
// Works with 2:
events.track("something", [["first", "a"], ["other", "b"]]);
// Works with 3:
events.track("something", [["first", "a"], ["other", "b"], ["some", "c"]]);
// Fails with 4:
events.track("something", [["first", "a"], ["other", "b"], ["some", "c"], ["fourth", 42]]);
// Error as desired −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^
But that may not have the best ergonomics.
CodePudding user response:
I got a solution using TuplifyUnion
from here:
I am not sure how "safe" this is (see the disclaimer). Using TuplifyUnion
is considered unsafe since the order may change at any time. Since the order is not important here and only the amount of elements matters in this case, I think this is ok to use here.
The solution allows 0-3 keys. If you want 1-3 keys just remove the TuplifyUnion<keyof T> extends [] ? T :
.
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type LastOf<T> =
UnionToIntersection<T extends any ? () => T : never> extends () => (infer R) ? R : never
type Push<T extends any[], V> = [...T, V];
type TuplifyUnion<T, L = LastOf<T>, N = [T] extends [never] ? true : false> =
true extends N ? [] : Push<TuplifyUnion<Exclude<T, L>>, L>
type MaxThreeProperties<T extends Record<string, any>> =
TuplifyUnion<keyof T> extends []
? T
: TuplifyUnion<keyof T> extends [any]
? T
: TuplifyUnion<keyof T> extends [any,any]
? T
: TuplifyUnion<keyof T> extends [any, any, any]
? T
: never
function track<T extends Record<string, any>>(
name: string,
params: MaxThreeProperties<T>
) {}
We basically put all keys into a tuple and then "manually" check the length of the tuple. This can be easily extended to other amounts of properties though it might get ugly.
One downside is the error message though:
Type 'string' is not assignable to type 'never'.(2322)
This may be confusing for someone using the function...
Here are some tests:
track('SOME_EVENT', {}) // works
track('SOME_EVENT', {a: ""}) // works
track('SOME_EVENT', {a: "", b: ""}) // works
track('SOME_EVENT', {a: "", b: "", c: ""}) // works
track('SOME_EVENT', {a: "", b: "", c: "", d: ""}) // ERROR
track('SOME_EVENT', {a: "", b: "", c: "", d: "", e: ""}) // ERROR
const a = {a: "", b: "", c: ""}
const b = {a: "", b: "", c: "", d: ""}
track('SOME_EVENT', a) // works
track('SOME_EVENT', b) // ERROR
CodePudding user response:
you can do that
export interface Events { name: string, params?: Record<string, string | number | unknown>}
function TestEvent (param:Events){}
TestEvent({name:'SOME_EVENT', params:{a:'a'}})