Typescript 具有类型别名的LinkedList 我走访了我认为非常吸引人的类型别名概念。然后我尝试运行以下代码段: 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;

Typescript 具有类型别名的LinkedList 我走访了我认为非常吸引人的类型别名概念。然后我尝试运行以下代码段: 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;,typescript,type-alias,Typescript,Type Alias,但现在我得到了一个错误: 错误TS2322:类型“{name:string;next:{name:string;next:{name:string;next:{name:string;next:undefined…”不能分配给类型“LinkedList” 我在哪里犯了错误?如果使用字符串空检查(使用strict或strictNullChecks选项),则undefined不能分配给LinkedList 最简单的选择是将next字段设置为可选 type LinkedList<T> =

但现在我得到了一个错误:
错误TS2322:类型“{name:string;next:{name:string;next:{name:string;next:{name:string;next:undefined…”不能分配给类型“LinkedList”


我在哪里犯了错误?

如果使用字符串空检查(使用
strict
strictNullChecks
选项),则
undefined
不能分配给
LinkedList

最简单的选择是将
next
字段设置为可选

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

interface Person {
    name: string;
}

var people: LinkedList<Person> =
    { name: "John", next: { name: "Jannet", next: { name: "Joanna", next: { name: "Adam", next: undefined } } } };
var s = people.name;
var s = people.next!.name;
var s = people.next!.next!.name;
var s = people.next!.next!.next!.name;

如果使用字符串空检查(使用
strict
strictNullChecks
选项),则
undefined
不可分配给
LinkedList

最简单的选择是将
next
字段设置为可选

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

interface Person {
    name: string;
}

var people: LinkedList<Person> =
    { name: "John", next: { name: "Jannet", next: { name: "Joanna", next: { name: "Adam", next: undefined } } } };
var s = people.name;
var s = people.next!.name;
var s = people.next!.next!.name;
var s = people.next!.next!.next!.name;

@TitianCernicovaDragomir的答案是正确的;通常,您需要某种基本大小写,以便您的链接列表可以具有有限的长度。但是,在不太可能的情况下,您希望创建符合原始
LinkedList
定义的类型安全的东西,您可以执行以下操作:

级大毒蛇{
name=“AlphaAndOmega”;

next=this;//@TitianCernicovaDragomir的答案是正确的;通常,您需要某种基本大小写,以便您的链接列表可以具有有限的长度。但是,在不太可能的情况下,您希望创建一个符合原始
链接列表
定义的类型安全的东西,您可以这样做:

级大毒蛇{
name=“AlphaAndOmega”;

next=this;//提香,是的,我使用strictNullChecks来查看它是否有帮助或使生活更麻烦。@MaciekLeks我两者都期望;)提香,是的,我使用strictNullChecks来查看它是否有帮助或使生活更麻烦。@MaciekLeks我两者都期望;)
function createLinkedList<T extends LinkedList<Person>>(p: T) {
    return p;
}
var people = createLinkedList({ name: "John", next: { name: "Jannet", next: { name: "Joanna", next: { name: "Adam"  } } } });
var s = people.name;
var s = people.next.name;
var s = people.next.next.name;
var s = people.next.next.next.name;