【发布时间】:2022-08-04 18:13:33
【问题描述】:
我正在使用打字稿来确保队列满足IQueue 接口:
export interface IQueue {
id: string;
handler: () => void;
}
const queues:IQueue[] = [
{ id: \'a\', handler: () => { } },
{ id: \'b\' }, // handler is missing, should be an error
];
我还想要一个 QueueId 类型,它是所有 id 的联合:
const queues = [
{ id: \'a\', handler: () => { } },
{ id: \'b\' },
] as const;
export declare type QueueId = (typeof queues[number])[\'id\'];
export const start = (queueId:QueueId) => {
...
};
start(\'z\'); // should be a typescript error
但我不能让他们一起工作。 QueueId 类型需要 as const 类型。有几篇文章建议进行 noop 强制转换,但我收到 readonly cannot be assigned to the mutable type... 错误。所以我试着让它可写,但它给出了一个“重叠不足”的错误:
type DeepWriteable<T> = { -readonly [P in keyof T]: DeepWriteable<T[P]> };
(queues as DeepWriteable<typeof queues>) as IQueue[];
有可能两者都做吗?
这是一个完整的例子:
-
this approach 是否满足您的需求?如果是这样,我可以写一个答案;如果没有,我错过了什么?
-
哇,是的 - 太棒了。在这里,我认为我擅长打字。我将不得不研究 asQueues 魔法
-
好的,当我有机会时,我会写一个解释它的答案。
-
我选择了一种更通用的方法,这种方法与您所做的事情的差异较小。如果你真的想让我写出
asQueues()的工作原理,我可以(但也许不是今天)
标签: typescript