Given the example below, the second parameter of the fn
function requires a class with a static attribute controle
and an instance attribute controle
, both of type number.
interface Base {
controle: number
new(...args: any[]): {
controle: number
}
}
function fn(constructor: Base) {
return [constructor];
}
fn(class {
static controle = 100;
controle = 100;
});
fn(class {
static controle = ""; // <--- throw type error
controle = ""; // <--- throw type
});
Considering the example below, the second parameter of the fn
function has the type Base<T>
where T
is a key of DocumentEventMap
. For instance, if T is "click", then the second parameter of the fn
function must be a class with a static attribute type
and an instance attribute type
, both of type "click".
type EventType = keyof DocumentEventMap;
interface Base <T extends EventType>{
type: T
new(...args: any[]): {
type: T
}
}
function fn(constructor: Base<"click">) {
return [constructor];
}
fn(class {
static type: "click" = "click";
type: "click" = "click";
});
fn(class {
static type: "abort" = "abort"; // <--- throw type error
type: "abort" = "abort"; // <--- throw type error
});
Here's my question: In the second example, I hard-coded "click" as the generic type. How can I make it a dynamic value? Please consider my attempt below:
type EventType = keyof DocumentEventMap;
interface Base <T extends EventType>{
type: T
new(...args: any[]): {
type: T
}
}
function fn<K extends EventType>(type: K, constructor: Base<K>) {
return [type, constructor];
}
fn("click", class {
static type: "click" = "click";
type: "click" = "click";
});
fn("click", class {
static type: "abort" = "abort"; // <--- should throw type error, but it doesn't
type: "abort" = "abort"; // <--- should throw type error, but it doesn't
});
Therefore, how can I correctly define the second parameter as a generic class based on the first parameter of a function?
I'm Brazilian, and my English may not be perfect, so feel free to correct my text if necessary.
Thank you