[英]Enforce single required property on Typescript interface, allow others
我正在创建一个通用的 WebSocket 组件。 我想要求Message
类型具有一个名为type
的必需属性。
export type Message = {
type: string;
[key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
};
该组件被赋予了一系列回调函数,当调用适当type
的Message
时会调用这些回调函数。
export interface Listeners {
[type: string]: (msg: Message) => void;
}
WebSocket 实现的代码片段:
...
ws.onmessage = (event: MessageEvent): void => {
console.log("[websocket] got raw message", event.data);
try {
const msg = JSON.parse(event.data);
if (listeners[msg.type]) {
console.log("[websocket] got message", msg);
listeners[msg.type](msg);
}
}
}
...
在使用 WebSocket 组件时,我想定义一个自定义类型是Message
类型的扩展,并包含type
属性。
interface GraphMessage extends Message {
id: string;
type: "initial" | "update";
chartType: "line" | string;
data: GraphPoint[];
}
我正在尝试像这样使用组件:
const handleUpdate = (msg: GraphMessage) => {}
const handleInitial = (msg: GraphMessage) => {}
const ws = await websocket("ws://localhost:9999/", {
initial: handleInitial,
update: handleUpdate
});
但是,我收到了一个打字稿错误:
TS2322: Type '(msg: GraphMessage) => void' is not assignable to type '(msg: Message) => void'.
Types of parameters 'msg' and 'msg' are incompatible.
Type 'Message' is not assignable to type 'GraphMessage'.
如何使Message
可分配到类型GraphMessage
?
编辑:我相信我已经找到了使Message
成为通用类型的解决方案。
type Message<T> = {
type: string
[key: string]: any
} & T
interface GraphMessage {
graphName: string
}
type Callback = (msg: Message<GraphMessage>) => void
const myBaseMessage = {
t...
TypeScript 正确地指出Type '(msg: GraphMessage) => void' is not assignable to type '(msg: Message) => void'
。
如果您的处理程序依赖于GraphMessage
但您只提供了一个Message
,这可能会导致运行时异常:
// Can, but doesn't have to include `id`
export type Message = {
type: string;
[key: string]: any;
};
interface GraphMessage extends Message {
id: string;
type: "initial" | "update";
}
const message: Message = {
type: 'foo',
}
const handler = (msg: GraphMessage): void => {
console.log(msg.type.toLocaleLowerCase());
}
如果我们这样做
handler(message); // Compile-time error
TypeScript 将防止抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.