We usually think of types as something that can define a single layer of an object: with an interface we normally specify a list of a few properties and their respective types. If any one of those properties is another object we must refer again to its type. This is a finite process, as eventually we will get to a flat object, that doesn’t reference any other objects. Trees and Linked Lists are dynamic data structures, that can have infinitely many levels of depth. A type alias in TypeScript can use generics and refer to itself - this can be used to create these potentially infinitely long data structures. We will also explore using Linked Lists for building a Redux time travelling debugger.
When I write
const actionNode1: LinkedNode<Action> = {
value: action1,
next: null,
prev: null,
}
I get the error Type 'null' is not assignable to type 'LinkedNode<Action>'.
for next and prev. That's what I thought would happen, so I'm wondering why your IDE isn't throwing an error. Shouldn't it be:
interface LinkedNode<T> {
value: T;
next: LinkedNode<T> | null;
prev: LinkedNode<T> | null;
}
Oh! I think you might have strict
or strictNullChecks
enabled in your tsconfig.json
- https://www.typescriptlang.org/tsconfig/#strictNullChecks
In which case you are 100% correct, your second example would be appropriate for stricter type checks. Thanks for pointing that out!
Yup, that was it I had strict
set.