是否可以将特定方法模式标记为 return 特定类型?

Is is possible to mark specific methods paterns to return a specific type?

是否可以在打字稿中定义一个接口,该接口将仅应用于以特定单词开头并使它们具有特定 return 类型的方法?我想到了类似的东西:

interface IPattern {
   [k: 'handle' + string]?: () => SomeClass
}

因此 class 实现 IPatten 并具有以 handle 开头的方法将被强制 return 一个 SomeClass 对象,而其他方法则不会,例如:

class ForcedClass implements IPattern{
   foo(): number; // ok
   handleFoo(): SomeClass; // ok
   handleBar(): number; // error
}

我知道可以将抽象 class 与我需要的所有方法一起使用,但是由于 handle + something 的组合用于许多不同的实现中,因此创建它会很冗长他们每个人的摘要;

您可以非常接近索引签名和模板文字类型:

interface IPattern {
   [k: `handle${string}`]: () => SomeClass
}
class ForcedClass implements IPattern{
   [k: `handle${string}`]: () => SomeClass
   foo(): number { return 0 } // ok
   handleFoo(): SomeClass { return "0 "} ; // ok
   handleBar(): number{ return 0 }  // error
}


new ForcedClass()['handleBaz'](); // this is ok, because of the index signature
new ForcedClass().handleBaz(); // this is ok, because of the index signature

Playground Link

索引方法的问题在于,虽然 class 成员是针对它进行验证的,但这也意味着您可以使用符合 handle${string} 模板文字类型的任何值进行索引,即使如果该成员实际上不属于 class.

另一种选择是使用一种类型来验证 class 的实际密钥而不添加索引签名:

type IPattern<T> = Record<Extract<keyof T, `handle${string}`>, () => SomeClass> {

class ForcedClass implements IPattern<ForcedClass>{
   foo(): number { return 0 } // ok
   handleFoo(): SomeClass { return "0 "} ; // ok
   handleBar(): number{ return 0 }  // error
}

new ForcedClass().handleBaz(); //error
new ForcedClass().handleFoo(); //ok

Playground Link