#Extend type properties to support recursion types.

8 messages · Page 1 of 1 (latest)

pearl remnant
#

I'm trying to create a class that I can register parameters to it, it works in the top level but fails in nested properties.

Take a look at the last line of the playground, that's my goal.
Thanks in advance

low spindleBOT
#
karif23#0

Preview:```ts
// Type definition for extending a scope with a name
type ExtendScope<T, S extends string> = T & {
// Inner scopes object with name as key and Scope interface as value
innerScopes: {
[s in S]: Scope
}
}

// Interface for a Scope
interface Scope {
...```

low spindleBOT
#
ascor8522#0

Preview:```ts
enum ComponentType {
FOO,
BAR,
}

interface IScope<
T extends Record<string, IScope> = {}

{
components: ComponentType[]
innerScopes: T
addComponent(...args: any[]): void
addScope<S extends string>(
scope: S
): asserts this is this & {
innerScopes: T & Record<S, IScope>
}
...```

oblique plover
#

@pearl remnant the error message is pretty clear

#

you cannot call the method addScope on level1
because addScope uses a generic which references itself (asserts this), and TS needs the whole type to be known and written down

#

you can solve that by storing level1 inside of a variable, and giving it an explicit type

#

but it kinda ruins the purpose

#

but tbh, this might be too much type magic for what you are trying to do
having all the types figured out is nice, but sometimes it's not possible
especially when you are calling methods that mutate the object and return it
you've kinda reached TS limits in terms of what's possible
you might want to re-think if knowing all declared scopes at compile time is worth it
or if it wouldn't be simpler to do a simple check at runtime