1

Given the following data:

const tree = {
    _size: 0,
    a: {
        _size: 0,
        b: {
            _size: 0,
        }
    },
    c: {
        _size: 0
    }
}

Is there a way to make it so that TypeScript understands that every key that is not _size is of type Dir ?

I would like to create a type that includes itself recursively. So far, I've got the following:

type Dir = {
    _size: number,
    [key: string]: /* Dir? */
}

Where I would like to comment out the "Dir" in order for it to recursively include itself. However, this is giving me the following error:

Property '_size' of type 'number' is not assignable to 'string' index type 'string'
  • 1
    I would suggest using a structure like `{ _size: number; children: Record }` instead. – kelsny Dec 07 '22 at 17:28
  • The problem is not the recursion, but the lack of a good way to say "every key that is not `_size`". See the answers to the linked question for possible ways to do it and alternatives. If you can refactor so that the dynamic keys do not coexist with `_size` in the same object, you probably should... your life will be much easier. – jcalz Dec 07 '22 at 17:30

0 Answers0