【发布时间】:2022-12-05 17:43:42
【问题描述】:
我有一个打字稿错误,说 .filter 没有签名。我不知道如何解决这个问题
interface IDevice {
deviceId: string;
deviceName?: string;
}
const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams) => {
rooms[userId] = rooms[userId]?.filter((id) => id !== deviceId);
})
更新:下面我添加了我所有的界面和加入房间的完整功能。我不确定如何构造我的类型,以便在设备断开连接时我可以使用 .filter 从列表中远程设备
const rooms: Record<string, Record<string, IDevice>> = {};
interface IDevice {
deviceId: string;
deviceName?: string;
}
interface IRoomParams extends IDevice {
userId: string;
}
interface ISendRequestParams {
userId: string;
options: any;
requestId: string;
}
interface IReturnRequestParams {
userId: string;
data: any;
requestId: string;
error: any;
}
const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams) => {
if (!rooms[userId]) rooms[userId] = {};
// console.log('device joined the room', userId, deviceId, deviceName);
rooms[userId][deviceId] = { deviceId, deviceName };
socket.join(userId);
io.sockets.to(userId).emit('get-devices', {
userId,
participants: rooms[userId]
});
socket.on('disconnect', () => {
console.log(`user left the room: roomId[${userId}], device[${deviceId}], deviceName[${deviceName}]`);
rooms[userId] = rooms[userId]?.filter((id) => id !== deviceId);
socket.to(userId).emit('device-disconnected', deviceName);
});
};
错误: 此表达式不可调用。 类型 'IDevice' 没有调用 signatures.ts(2349)
【问题讨论】:
-
rooms的类型是什么?什么是IRoomParams?如果我们假设IRoomParams中的deviceId与IDevice中的一样是string,代码的编写使得rooms[userId]需要具有类型undefined | string[](或null | string[],或全部三种) .可以? -
你能提供更多代码吗?什么是房间(及其类型)? IRoomParams 是什么?当您在对象而不是数组上使用
.filter时,通常会发生此错误 -
当询问错误消息时,请务必将完整的错误消息复制并粘贴到问题中。只是“没有签名”并不能真正告诉我们太多(某物, 但并不多)。
-
我更新了问题以反映加入房间的完整功能和完整的错误消息
-
感谢那!
rooms[userId]的类型是undefined | Record<string, IDevice>,不是@Paul-Marie说的数组类型。您使用filter数组,不是简单的对象。
标签: typescript