Answer the question
In order to leave comments, you need to log in
How to exclude a specific class from a type in Typescript?
There is the following code:
type BaseType<T> = { new(): T };
class Base {
go(...args: any[]): void { }
}
const queue: any[] = [];
function foo<T extends Base>(target: BaseType<T>, ...args: Parameters<T['go']>): T;
function foo<K>(instance: K): K;
function foo<T extends Base, K>(target: BaseType<T> | K, ...args: Parameters<T['go']> | any[]): T | K {
if (target instanceof Object && target.prototype instanceof Base) {
const instance = new target();
instance.go(args);
queue.push(instance);
return instance;
} else {
queue.push(target);
return <K>target;
}
}
class BaseChild extends Base {
go(a: number, b: string) { }
}
foo(() => {}); // Тут все ок
foo(BaseChild, 123, 'hi'); // Тут все ок
foo(BaseChild); // Тут должна выскакивать ошибка, так как по задумке, если первый параметр Base, то тогда ожидаются далее параметры ...args: Parameters<T['go']>
function foo<K>(instance: K): K;
that the parameter instance
can contain anything, but not Base
its heirs?
Answer the question
In order to leave comments, you need to log in
In typescript, structural typing. He doesn't care what class the object spawned. If the generated object structurally coincides with the signature (the signatures of all properties and methods are the same), then such an object passes by the condition:
class Foo {
a!: number;
b!: number;
}
function bar(arg:Foo) {};
const randomObj = {a:1, b:2, c:5};
bar(randomObj); // ok
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question