Summary: I have a tuple type like this:
[session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string]
and I want to convert it to an object type like this:
type StreamAgentParameters = {
session: SessionAgent
streamID: string
isScreenShare: boolean
connectionID: string
videoProducerOptions: ProducerOptions | null
connection: AbstractConnectionAgent
appData: string
}
Is there a way to do that?
I want to create a factory function for tests for a class to simplify the setup.
export type Factory<Shape> = (state?: Partial<Shape>) => Shape
I want to avoid manually typing out the parameters for the class, so I looked for possibilities to get the parameters for the constructor. And what do you know, there is the ConstructorParameters
helper type. Unfortunately, it returns a tuple instead of an object.
Therefore the following doesn't work because a tuple is NOT an object.
type MyClassParameters = ConstructorParameters<typeof MyClass>
// ↵ [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string]
const createMyClassParameters: Factory<MyClassParameters> = ({
session = new SessionAgent(randomRealisticSessionID()),
streamID = randomRealisticStreamID(),
isScreenShare = false,
connectionID = randomRealisticConnectionID(),
videoProducerOptions = createPopulatedProducerOptions(),
connection = new ConnectionAgent(
new MockWebSocketConnection(),
'IP',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
),
appData = 'test',
} = {}) => ({
session,
streamID,
isScreenShare,
connectionID,
videoProducerOptions,
connection,
appData,
})
I tried creating a helper type that converts a tuple to an object, but my best attempt was this (and it didn't work).
type TupleToObject<T extends any[]> = {
[key in T[0]]: Extract<T, [key, any]>[1]
}
How can I solve this problem?