gpt4 book ai didi

generics - 在 TypeScript 的泛型函​​数中推断映射类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:35 24 4
gpt4 key购买 nike

使用 this StackOverflow post例如,我实现了一个类型化的事件系统。简化后,它看起来像:

interface MyTypeMap {
FOO: string;
BAR: number;
}

我正在尝试使用此映射创建事件处理程序:

function handleEvent<T extends keyof MyTypeMap>(eventKey: T, eventMsg: MyTypeMap[T]) {
switch(eventKey) {
case('FOO'):
// TS believes that eventKey is of type 'never'
// TS believes that eventMsg is 'string|number'
break;
case('BAR'):
// TS believes that eventKey is of type 'never'
// TS believes that eventMsg is 'string|number'
break;
}
}

当从外部调用此函数时,TypeScript 的行为符合预期。例如:

// These work as desired
handleEvent('FOO', 'asdf');
handleEvent('BAR', 5);

// These throw compile errors as desired
handleEvent('FOO', 6);
handleEvent('BAR', 'i am not a string');

然而,TypeScript 的函数内部非常困惑。它似乎相信任何 case 语句都不会被击中。为什么 TypeScript 无法正确推断函数内部的类型,尽管它可以很好地处理外部调用?

最佳答案

目前没有办法根据另一个变量的类型来限制一个变量的类型。删除 handleEvent 的通用参数 T 后可以获得最好的结果(不知道为什么它会导致 typescript 将 eventKey 类型推断为 never) 是

function handleEvent(eventKey: keyof MyTypeMap, eventMsg: MyTypeMap[typeof eventKey]) {
switch(eventKey) {
case ('FOO'):
const a1 = eventKey; // a1 has type 'FOO'
const m1 = eventMsg; // m1 has type string|number
break;
case('BAR'):
const a2 = eventKey; // a2 has type 'BAR'
const m2 = eventMsg; // again, m2 has type string|number
break;
}
}

所以当eventMsg所依赖的变量类型eventKey受到限制时,编译器不会限制eventMsg的类型。不过,如果可以的话,那就太好了。

但是如果您愿意使用将消息类型映射到处理程序而不是 switch 语句的对象,这里是工作原型(prototype)(目前限制为每种消息类型只有一个处理程序,但我相信可以轻松扩展):

class Dispatcher {    
on<
MessageType extends keyof AppMessageMap
>(
messageType: MessageType,
handler: (message: AppMessageMap[MessageType]) => void
): void {
this.handlerMap[messageType] = handler;
}

handlerMap: {[s: string]: (message: AppMessageMap[keyof AppMessageMap]) => void} = {};

emit<MessageType extends keyof AppMessageMap>(messageType: MessageType, message: AppMessageMap[MessageType]) {
const handler = this.handlerMap[messageType];
if (handler) {
handler(message);
}
}
}

/* messages.ts */

interface AddCommentMessage {
commentId: number;
comment: string;
userId: number;
}

interface PostPictureMessage {
pictureId: number;
userId: number;
}

interface AppMessageMap {
"ADD_COMMENT": AddCommentMessage,
"POST_PICTURE": PostPictureMessage
}

/* app.ts */
const dispatcher = new Dispatcher();


dispatcher.on("ADD_COMMENT", (message) => {
console.log(`add comment: ${message.comment}`);
});
dispatcher.on("POST_PICTURE", (message) => {
console.log(`post picture: ${message.pictureId}`);
});

dispatcher.emit('ADD_COMMENT', {
comment: 'some comment',
commentId: 2,
userId: 3
});
dispatcher.emit('POST_PICTURE', {
pictureId: 4,
userId: 5
});

关于generics - 在 TypeScript 的泛型函​​数中推断映射类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43879572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com