Skip to content

Wrong type inference, returns the base class type instead of the child class typeΒ #57286

Closed
@denis-migdal

Description

@denis-migdal

πŸ”Ž Search Terms

None

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________

⏯ Playground Link

Playground Link

πŸ’» Code

// BUG1:
{
	class Base {
		get self(): Base { return this }
	}
	class Child extends Base {
		override get self(): Child { return this }
		child = true;
	}

	function convert<T extends Base>(X: T) { // implicitly returns Base["self"] instead of T["self"]
		return X.self;
	}

	const value = convert( new Child() );
	// expected: typeof value = Child.
	// got: typeof value = Base.
	
	
	function convert2<T extends Base>(X: T): T["self"] {
		return X.self;
	}

	const value2 = convert2( new Child() );
	// typeof value = Child.
}

// BUG2:
{
	class BaseClass<V> {
		protected fake(): V { throw new Error("") }
	}

	class Klass<V> extends BaseClass<V>{
		child = true;
    }

	type Constructor<P extends BaseClass<number>> = new () => P;
	type inferTest<T> = T extends Constructor<infer P> ? P :never;

	type U = inferTest<Constructor<Klass<number>>> // U = Klass<number>
}
{
	class BaseClass<V> {
		protected fake(): V { throw new Error("") }
	}

	class Klass<V> extends BaseClass<V>{
		child = true;
    }

	type Constructor<V, P extends BaseClass<V>> = new () => P;
	type inferTest<V, T> = T extends Constructor<V, infer P> ? P :never;

	type U = inferTest<number, Constructor<number, Klass<number>>>
	// got: U = BaseClass<number>
	//expected: U = Klass<number>
}

πŸ™ Actual behavior

Bug1: It seems that when calling methods in generic function foo<T extends Base>(t: T) :

t.foo() // viewed as method Base.foo()
// instead of being viewed as T.foo() with T extends Base.

Bug2: For type inference, it seems that adding a generic parameters confuses TS.

πŸ™‚ Expected behavior

Cf code.

Additional information about the issue

Related to issue #57102

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions