2

I have next object

const obj = {
 name: 'First',
 age: 22,
}

This object has the next interface

interface ITask {
 name: string,
 age: number
}

but after some data mapping I create a recursive object like this

const obj = {
 name: 'First',
 age: 22,
 next: {
   name: 'Second',
   age: 12,
   next: { EMPTY OBJECT WHEN END }
 }
}

I try type this object this way, but it doesnt work

type IRecursiveTask =  {
        [key: string]: IRecursiveTask
} & ITask

1 Answer 1

10

type defines a type aliases, and type aliases cannot reference themselves. However, interface can.

interface IRecursiveTask {
  name: string;
  age: number;
  next: IRecursiveTask | {};
}
Sign up to request clarification or add additional context in comments.

2 Comments

The type should work, but the reason you describe is not the reason why. an type alias works just fine. tsplay.dev/mbAXPN This works because the type is recursive in a known property rather than index signature.
@AlexWayne, you should have put that as an answer!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.