【发布时间】:2021-11-04 04:34:13
【问题描述】:
总结:我有一个这样的元组类型:
[session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string]
我想把它转换成这样的对象类型:
type StreamAgentParameters = {
session: SessionAgent
streamID: string
isScreenShare: boolean
connectionID: string
videoProducerOptions: ProducerOptions | null
connection: AbstractConnectionAgent
appData: string
}
有没有办法做到这一点?
我想为一个类的测试创建一个factory function 以简化设置。
export type Factory<Shape> = (state?: Partial<Shape>) => Shape
我想避免手动输入类的参数,所以我寻找获取构造函数参数的可能性。你知道吗,有ConstructorParameters 辅助类型。不幸的是,它返回的是一个元组而不是一个对象。
因此以下内容不起作用,因为元组不是对象。
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,
})
我尝试创建一个将元组转换为对象的辅助类型,但我最好的尝试是这样(但没有成功)。
type TupleToObject<T extends any[]> = {
[key in T[0]]: Extract<T, [key, any]>[1]
}
我该如何解决这个问题?
【问题讨论】:
标签: typescript object parameters constructor tuples