#Set a type of a function based on a callback with constraints?

1 messages · Page 1 of 1 (latest)

fair ravine
#

I have this function which I want to make more type safe. The first argument is a callback and rest of the arguments which will be passed to the function (Maybe pre processed or stored passed later, but to for now lets assumed it immediately called).


//The callback type
type component<T extends Attr = Attr, U extends node = node, R extends node = node>= ((attr: T, ...content: U[]) => R)

export function c(name: component, attr: Attr /*The first param of name*/, ...content: node[]/* Remaining Parameters name*/): node /*Return Type of name*/ {
    return name(attr, content)
}

Google gives me an option using ReturnType<T> but that only works when the return type is any.

Any solutions here?

plush dock
#

the solution will involve generics

#

!hb generics

tall cloakBOT
plush dock
#

what is the node type in your example?

fair ravine
#

Its a union type with several types on of them is an array to self

plush dock
#

can you share the type definition for node? also is Attr the DOM type of that name or something else?

fair ravine
# plush dock the solution will involve generics

I did try that initially but it did not work. Thats why the component type has 3 type arguments. But U type will always break if I use multiple types(that all valid by the Union node). It will always detect the first element as the type.

barren berry
#

tbh

fair ravine
#

Its a vdom implentation

barren berry
#

you can even avoid component completely

#
export function c<T extends Attr = Attr, U extends node[] = node[], R extends node = node>(
  name: (attr: T, ...content: U[]) => R,
  attr: T, ...content: U
): R {
    return name(attr, ...content);
    //                ^^^ i'm assuming leaving these out was a typo
}
fair ravine