【问题标题】:Typescript: how can I exclude methods from the index signature of classes?打字稿:如何从类的索引签名中排除方法?
【发布时间】:2020-06-27 14:47:41
【问题描述】:

我有一个可以像这样由用户扩展的类:

class Foo {
   extendFoo(key: string, value: string) {
      this[key] = value; //<==typescript error: missing index signature
   }
}

如您所见,this 可以使用字符串进行扩展。 问题是打字稿抱怨因为我没有索引签名,所以我尝试添加一个:

class Foo {
   [key: string]: string;

   extendFoo(key: string, value: string) {  //<==typescript error: extendFoo is not a string
      this[key] = value;
   }
}

如何添加索引签名,但仍允许在我的类中使用方法?

当然,我可以将索引签名更改为[key: string]: string | Function,但这不正确——任何未知键都必须是字符串。如何从索引签名中仅排除 extendFoo

class Foo {
   [key: string]: string | Function;

   extendFoo(key: string, value: string) {
      this[key] = value;
   }
}

const test = new Foo();
test['some unknown prop'].includes('test'); //<== typescript error: 'Property 'includes' does not exist on type 'Function'

顺便说一句,我知道扩展 this 是一种不好的模式,但我正在将旧代码转换为打字稿并且别无选择。

【问题讨论】:

  • 这能回答你的问题吗? Typescript index signature and methods
  • this 适合您吗?如果是这样,我会写下来。
  • @DaGardner,我在问这个问题之前偶然发现了这个链接,但这对我的情况不利。建议的解决方案是我在第三个代码中剪掉的,我解释了为什么它对我来说不够好。
  • @jcalz,这是一个有趣的解决方案。如何在 cmets 中发送链接?太长了,不想和大家分享了

标签: typescript class methods index-signature


【解决方案1】:

我认为 TS 无法以完全类型安全的方式完全按照您的意愿行事,因为密钥的类型必须是 stringnumber。由于您的方法众所周知且异常,因此@ts-ignore TS 错误可能没问题?

class Foo {
    [key: string]: string | null;

    // @ts-ignore
   extendFoo(key: string, value: string) {
      this[key] = value;
   }
   // @ts-ignore
}


const test = new Foo();
test['some unknown prop']?.includes('test'); // <- No error
test.extendFoo("asdf", "asdf"); // <- works, too

我知道这并不理想,但至少您不必在每个呼叫站点上进行投射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2018-12-15
    • 2019-09-21
    • 2021-03-06
    • 2018-04-19
    相关资源
    最近更新 更多