参数的使用 失败

问题描述 投票:1回答:1
class Example { 
  alpha(props: { check: boolean }) { 
    // noop
  }

  beta(props:
    Partial<Parameters<this['alpha']>[0]> // this fails
    // Partial<Parameters<Example['alpha']>[0]> // this works
    // Partial<{ check: boolean }> // this works
  ) { 
    // noop
  }

  useBeta(props:
    { check?: boolean | undefined }
  ) { 
    const { check } = props
    return this.beta({ check })
  }

}

我一直在使用this来引用方法的输入参数,但是我发现它不起作用的情况,我想对其进行记录/对这种情况为什么不起作用有一些想法。

typescript
1个回答
0
投票

我只是将{check: boolean}提取到某个接口并将其传递。无论如何,这不是一个问题。问题是为什么它不适用于this

您不能保证this将成为Example实例。您可以随时通过applycall通过。

class Example {
  beta(props: Partial<{ check: boolean }>) { 
    console.log(this);
  }
}

const example = new Example();
example.beta({ check: true });
// Object {  }

Example.prototype.beta.apply("not an Example object", [{ check: true }]);
// "not an Example object"
© www.soinside.com 2019 - 2024. All rights reserved.