为什么打字稿代码是(或不是)循环依赖?

下面的代码使我感到困惑,因为我认为这可能是循环依赖,但是Typescript允许下面的代码。谁能解释这段代码的实际作用?

interface A extends Array<B> { };
type B = A;
wwjazrael 回答:为什么打字稿代码是(或不是)循环依赖?

TypeScript允许递归定义,甚至允许interface A extends Array<A> { };

我不知道此特定定义在哪里有用,但这是在TypeScript中引入该定义的示例。

原始来源:

https://github.com/microsoft/TypeScript/pull/33050

type ValueOrArray<T> = T | Array<ValueOrArray<T>>;

const a0: ValueOrArray<number> = 1;
const a1: ValueOrArray<number> = [1,[2,3],[4,[5,[6,7]]]];

type HypertextNode = string | [string,{ [key: string]: any },...HypertextNode[]];

const hypertextNode: HypertextNode =
    ["div",{ id: "parent" },["div",{ id: "first-child" },"I'm the first child"],{ id: "second-child" },"I'm the second child"]
    ];

type Json = string | number | boolean | null | Json[] | { [key: string]: Json };

let data: Json = {
  caption: "Test",location: { x: 10,y: 20 },values: [0,10,20]
}

JavaScript允许对象采用任何类型的对象的形状,而TypeScript尝试允许在大多数情况下进行类型检查。上面的示例是这种模式的完美案例,其中递归类型定义很有意义。

由于类型仅保留在TypeScript编译上下文中,因此它们不是循环依赖项,因为在运行时所有类型都消失了,而所有剩下的都是纯JavaScript。

本文链接:https://www.f2er.com/3068954.html

大家都在问