如何将新键和值分配给已在typescript中定义的对象

eqoofvh9  于 2022-12-14  发布在  TypeScript
关注(0)|答案(1)|浏览(131)

我正在从js迁移到ts,我通过在typescript中创建discord bot(以了解环境)来实现这一点。当尝试在已由类创建的对象上创建新键时,我收到Property 'key' does not exist on type 'object'错误
代码示例:

import { Client } from "discord.js";
const client = new Client({
  intents: [permissions],
});
client.handler = new CommandManager()
//error: Property 'handler' does not exist on type 'Client<boolean>'

这对我来说很奇怪,因为在javascript中,你可以为一个已经创建的对象分配新的键。我试过使用Object.assign()

Object.assign(client, { handler: new CommandManager() })

并且最初它工作正常,当我使用console.log()时,键实际上在对象内部,但是当我试图在代码中调用该值时,返回了相同的错误。

Object.assign(client, { handler: new CommandManager() })
console.log(client)
//has .handler object inside it
client.handler.stuff
//error: Property 'handler' does not exist on type 'Client<boolean>'

我想了解为什么会发生这种情况,以及是否有解决方案可以在对象内部分配键,以便在代码中使用它

f8rj6qna

f8rj6qna1#

通过创建一个自定义客户端类来扩展discord的客户端类可以解决这个问题。

import { Client, ClientOptions } from 'discord.js';

class CustomClient extends Client {
  handler: CommandManager = new CommandManager()
  constructor(options: ClientOptions){
    super(options);
  }
}

相关问题