ESLint TypeScript 接口 Spread Operator

ESLint TypeScript Interface Spread Opreator

我最近在我的 TypeScript 项目中安装了 ESLint,它做得很好。然而,我却运行陷入了困境。我有一个 RunFunction 的接口,它是实现我的 Discord 机器人的核心部分。我以前 unknownany。但是,我根据 ESLint 的建议更改了此设置。但是,现在我不确定如何在实现中消除转换错误:

Type '(client: Bot, info: string) => Promise<void>' is not assignable to type 'RunFunction'.
  Types of parameters 'info' and 'args' are incompatible.
    Type 'unknown' is not assignable to type 'string'.ts(2322)

以下是我使用的源文件:

RunFunctionStorage.ts

import Bot from '../client/Client';

export default interface RunFunction {
    (client: Bot, ...args: unknown[]): Promise<void>;
}

WarnEvent.ts

import Bot from '../../client/Client';
import RunFunction from '../../interfaces/RunFunctionStorage';

export const run: RunFunction = async (
    client: Bot,
    info: string
): Promise<void> => {
    client.logger.info(info);
};

export const name = 'warn';

ReadyEvent.ts

export const run: RunFunction = async (
    client: Bot,
    message: Message
): Promise<void> => {
    ...
}

...

通过我对 Whosebug 的研究,我知道我可以简单地将 unknown 作为 info 的类型。然而,我对该解决方案的问题是,它会让我不知道 VSCode 提供给我的提示中的类型。我也调查了 info: string | unknown 但这对我来说似乎很模糊。有没有更优雅的解决方法?

不要想太多。有几种方法可以解决这个问题

第一个

修复它的最简单方法是使用名为

的内置界面

可调用函数

你只需要这样使用就可以了

export const run: CallableFunction = // yow function

问题是,你的 运行 函数不会告诉你它需要什么参数,好处是你可以传递你想要的任何东西

第二

创建你自己的类型

export type RunFunction = <T,R>(client: Bot, info:T) => Promise<R>

解决方案

这可以用泛型来完成


export default interface RunFunction<T> {
    (client: Bot, ...args: T): Promise<void>;
}

这个简单的 T 是一个占位符,它可以是任何你想要的,例如,如果你需要传递一个字符串,你必须像这样指定

/// for functions and stuff I prefer types, I only use interfaces for objs or classes 

export type RunFunction =<T> (bot: Bot, params: T)=>Promise<void>;


And now that I think you don’t even need that, you can create the function directly 

function runFunction <T>(boy:Bot, params:T) {
//Yow code

}
…
/// here you are saying list is an array of strings
runFunction<string[]>(instance, list)

// here is an object 
unFunction<string[]>(instance, list)

Now when you call the function you’ll get type hints

@Mahyar Mirrashed,

不幸的是,我得到的最接近的是:

export default interface RunFunction<R extends unknown> {
  (client: Bot, ...args: R[] ): Promise<void>
}
export const run: RunFunction<string> = async (
    client: Bot,
    info: string
): Promise<void> => {}


export const fly: RunFunction<Message> = async (client: Bot, info: Message): Promise<void> => {}

这与您在 VSCode / Typescript Intellisense 中想要的非常接近,但不完全是您想要的。您会在建议中看到一个数组,而不是单个对象。

我发现的另一个解决方法是:

export default interface RunFunction<R extends unknown[]> {
  (client: Bot, ...args: R ): Promise<void>
}


export const run: RunFunction<[string]> = async (
    client: Bot,
    info
): Promise<void> => {
  
}

export const fly: RunFunction<[Message]> = async (client: Bot, info): Promise<void> => {}

这个更接近你想要的,但它将第二个参数修改为 arg_0, arg_1 而不是你保留的名称,例如 info