3

我有一个可以由用户扩展的类,如下所示:

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,但是我正在将遗留代码转换为打字稿并且别无选择。

4

1 回答 1

0

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

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

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

于 2020-03-16T14:07:11.923 回答