在 TypeScript 中输入分支/叶子结构

问题描述 投票:0回答:1

在 TypeScript 中我有:

type Leaf = string[];
type Branch = { [id: string]: Branch | Leaf };

let someBranch:Branch;
let leafOrBranch:Branch|Leaf = someBranch.someSubBranch.someSubSubBranch.someLeafOrBranch;

这给了我以下错误(这是有道理的):

Property 'someSubSubBranch' does not exist on type 'Branch | Leaf'.
  Property 'someSubSubBranch' does not exist on type 'Leaf'.ts(2339)

我可以做

let someLeafOrBranch:Branch|Leaf = ((someBranch.someSubBranch as Branch).someSubSubBranch as Branch).someLeafOrBranch;

...但这很快就会变得烦人。

有没有办法更改类型,以便我可以直接调用

someBranch.someSubBranch.someSubSubBranch.someLeafOrBranch
而不给出任何错误?

typescript tree
1个回答
0
投票

如果您确定初始分支具有您期望的结构,您可以这样输入,编译器将不会发出相应的诊断信息:

TS游乐场

declare const someBranch: {
  someSubBranch: {
    someSubSubBranch: {
      someLeafOrBranch: Branch | Leaf;
    };
  };
};

const leafOrBranch = someBranch.someSubBranch.someSubSubBranch.someLeafOrBranch;
//    ^? const leafOrBranch: Branch | Leaf

但是,如果您不确定初始分支结构,那么使用一系列类型断言只会抑制有关可能导致运行时异常的语法的有用编译器诊断。

您也可以使用一个函数来迭代索引到您的分支,如下所示,通过提供对应于嵌套分支/叶子的属性访问器数组:

TS游乐场

function getNested(
  branch: Branch,
  propertyAccessors: readonly string[],
): Branch | Leaf {
  let result = branch as Branch | Leaf;
  for (const prop of propertyAccessors) {
    if (!Array.isArray(result)) {
      const child = result[prop];
      if (typeof child === "object") {
        result = child;
        continue;
      }
    }
    throw new Error(`Invalid porperty accessor: "${prop}"`);
  }
  return result;
}

declare const someBranch: Branch;
const leafOrBranch = getNested(someBranch, [
  "someSubBranch",
  "someSubSubBranch",
  "someLeafOrBranch",
]);

© www.soinside.com 2019 - 2024. All rights reserved.