Typescript: Relax the rule on the compiler side that all declarations have the same constraint

Created on 14 Nov 2017  路  8Comments  路  Source: microsoft/TypeScript

Originally reported in https://github.com/Microsoft/TypeScript/issues/14840

Consider WeakSet for instance.. today it is defined as interface WeakSet <T> {...}. This is incorrect, as it allows for patterns like const s = new WeakSet<string>(); s.add("foo"); which throws at runtime; the correct definition for WeakSet is interface WeakSet<T extends object> { .. }.

Changing this definition will cause errors in files that redefine WeakSet to add additional members to it.

Error: All declarations of WeakSet must have identical type paramters

The proposal here is to allow type parameter declarations to skip constraints. conflicting constraints should still be reported as errors.

Committed Fixed Suggestion good first issue help wanted

Most helpful comment

this has nothign to do with instantiations.. it is about declarations..

interface A<T> {}
interface A<T extends number> {}

today this is an error. this issue is to relax the check and treat it as:

interface A<T extends number> {}
interface A<T extends number> {}

Also note that mismatched constraints is still an error:

interface B<T extends number> {}
interface B<T extends string> {}

All 8 comments

Big fan 馃憢 馃憢 馃憢

Does that mean that, when a constraint is not specified, that it should "inherit" the most specific constraint found elsewhere? Or does that only apply on instantiation?

this has nothign to do with instantiations.. it is about declarations..

interface A<T> {}
interface A<T extends number> {}

today this is an error. this issue is to relax the check and treat it as:

interface A<T extends number> {}
interface A<T extends number> {}

Also note that mismatched constraints is still an error:

interface B<T extends number> {}
interface B<T extends string> {}

Easy PR for anyone who wants to take it, or we can pick it up in a bit

Where would one look to start tackling this?

@RichiCoder1 there's a function areTypeParametersIdentical in src/compiler/checker.ts:22351
That looks like a good place to start.

thanks @HerringtonDarkholme !

I noticed the behavior is order dependent: it's an error if the first declaration skips the constraint. In fact, mhegazy's example doesn't work. ~I don't think this is intentional, so I filed a new issue: #23909.~ It is intentional according to the description of #20883, for better or for worse.

Was this page helpful?
0 / 5 - 0 ratings