Nicolas S.Xu Nicolas S.Xu - 2 months ago 22
TypeScript Question

Typescript type intersection in type alias

Here is the example from official document in type alias section.

type LinkedList<T> = T & { next: LinkedList<T> };

interface Person {
name: string;
}

var people: LinkedList<Person>;
var s = people.name;
//var s = people.next.name;
//var s = people.next.next.name;
//var s = people.next.next.next.name;


when I try this example it generates the following error:

TypeError: Cannot read property 'name' of undefined


people is a linkList type. How to correctly fill the people link list?

Answer

You should assign it a value, just declaring type is not enough. For example:

var people: LinkedList<Person> = {name: "Alf", next: {name: "Tim", next: null}};