代码如下,想要实现 Message 中:playload 的类型取决于 type 的值
下面已有的写法是不行的。
interface PayloadMap {
join: PeerInfo;
offer: RTCSessionDescriptionInit;
answer: RTCSessionDescriptionInit;
icecandidate: RTCIceCandidateInit;
leave: PeerInfo;
}
// 客户端发送,服务端接受的数据格式
interface Message {
type: 'join' | 'offer' | 'answer' | 'icecandidate' | 'leave';
nick: string;
id: string;
// playload 的类型取决于 type 的值
payload: PayloadMap[Message['type']];
}
比如:
const m: Message = {
type: 'join',
nick: 'Fuck',
id: '123456',
payload: {
// 此时 payload 应该是 PeerInfo 类型
}
}
1
rabbbit 2022-01-21 20:57:04 +08:00 1
interface Foo {
} interface Bar { } interface PayloadMap { join: Foo; offer: Bar; } type Message = { [k in keyof PayloadMap]: { type: k; payload: PayloadMap[k]; } }[keyof PayloadMap]; const m: Message = { type: 'join', payload: { } } const n: Message = { type: 'offer', payload: { } } |
3
fifa666 2022-04-14 11:01:49 +08:00
interface PayloadMap {
join: 'join'; offer: RTCSessionDescriptionInit; answer: RTCSessionDescriptionInit; icecandidate: RTCIceCandidateInit; leave: 'leave'; } interface Message<T, P extends keyof T> { type: P; nick: string; id: string; payload: T[P]; } const m: Message<PayloadMap, 'join'> = { type: 'join', nick: 'Fuck', id: '123456', payload: "join" }; |