防止在另一种方法中使用一种方法

时间:2018-10-19 10:46:50

标签: typescript

我想防止在单独使用类型的另一种方法(baz)中使用一种方法(bar),因为出于某些原因(例如出于某种原因),这是不可取的导致无限递归。我宁愿避免运行时检查。

此方法有效,但需要在实现中指定this,编写Foo的开发人员应了解该限制:

abstract class AbstractFoo {
    abstract bar(): void;

    baz() {
        this.bar();
    }
} 

class Foo extends AbstractFoo {
    bar<T extends this & { baz: never }>(this: T) {
        this.baz(); // restriction exists here
    }
}

我想推断thisbaz中限制了bar的使用,这是行不通的:

abstract class AbstractFoo {
    abstract bar<T extends this & { baz: never }>(this: T): void;

    baz() {
        (this as any).bar(); // restriction exists here
    }
} 

class Foo extends AbstractFoo {
    bar() {
        this.baz(); // restriction doesn't exist here
    }
}

目标是通过类型检查通知不了解限制的开发人员,因此代码段1不是一个好的选择。

可以通过继承或其他不需要在this实现中指定Foo类型的方式施加此限制吗?

如果存在可以跟踪进度的阻塞TypeScript问题,欢迎参考。

1 个答案:

答案 0 :(得分:1)

如果隐藏原始[UIView animateWithDuration:(timeYouWantAnimate - 0.3f) animations:^{ [nameOfView setFrame:CGRectMake(0,spaceYouWantMove like -100, self.view.with, self.view.height)]; } 并且仅公开允许扩展AbstractFoo的函数,那么如果未在栏上指定AbstarctFoo,则可以使用一些条件类型来获取错误:

this

这不能解决从abstract class AbstractFoo { abstract bar<T extends this & { baz: never }>(this: T): void; baz() { (this as any).bar(); // restriction exists here } } type ValidateThisOfBar<T extends new (...args: any[]) => any> = InstanceType<T> extends { bar(this: infer TThis): void } ? TThis extends {baz: never} ? T: "method bar does not have this defined": never; export function createFoo<T extends new (...args: any[]) => any>(creator : (base: typeof AbstractFoo) => T & ValidateThisOfBar<T>): ValidateThisOfBar<T> { return creator(AbstractFoo) as any; } const Foo = createFoo(b => class extends b { // Type 'typeof (Anonymous class)' is not assignable to type '"method bar does not have this defined"'. bar() { this.baz(); } }); type Foo = InstanceType<typeof Foo> new Foo() // error Foo is never const Foo2 = createFoo(b => class extends b { bar<T extends this & { baz: never }>(this: T) { this.baz(); // error here } }); type Foo2 = InstanceType<typeof Foo> 派生的类的问题。