microsoft / microsoft/TypeScript

Different behavior when declare property or method in a class about covariance

未关闭
#42,002 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Docs
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

TypeScript Version: 4.1.2

Search Terms: In ts doc - type compatibility, it seems like not mentioned about this.

Code

class M1 {
  c: number = 1;
}

export class M2 extends M1 {
  a: number = 1;
}

type Func<M extends M1> = (m: M) => number;

interface IFunc<M extends M1> {
  func1?: Func<M>,
  func2: Func<M>,
}

class R1<M extends M1 = M1> implements IFunc<M> {
  // when delete this property, it will be no error.
  public func1 = (m: M) => {
    return m.c
  }

  public func2(m: M) {
    return m.c
  };
}

type IRConstructor<M extends M1, R extends R1<M>> = new () => R;

export class R2 extends R1<M2> {
}

type A = IRConstructor<M1, R1>;

let a1: A = R2; // error: Type 'typeof R2' is not assignable to type 'IRConstructor<M1, R1<M1>>'.

console.log(a1);

Expected behavior:

Should declare a property or a method in class has same behavior? I'm not sure...

Actually I want to know how can I make these code without error when I have to use functional property.

Actual behavior:

When you just decalre a method which is compatible with IFunc<M1>, it will be fine. But when you declare a functional property which is compatible with IFunc<M1>, it will be an error.

Playground Link:

Or, you can see playground

Related Issues:

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Issue 中链接的 TypeScript Playground 复现和 Issue 中引用的 handbook「Type Compatibility」部分开始。比较 generic class 在 functional property 形式和 method 形式下报告的行为,然后确定这种差异是否是有意的;完成的要求是确定预期行为,并在 compiler 或 documentation 中提供相应的覆盖。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
需要澄清
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。