microsoft / microsoft/TypeScript
Different behavior when declare property or method in a class about covariance
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground reproduction and the Type Compatibility handbook section referenced in the issue. Compare the reported generic-class behavior for the functional property and method forms, then establish whether the difference is intentional; done requires a decided expected behavior and corresponding compiler or documentation coverage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100