typescript - 根据 typescript 函数中的另一个参数限制一个参数的类型

标签 typescript

interface INavigation {
  children: string[];
  initial: string;
}

function navigation({ children, initial }: INavigation) {
  return null
}

我有一个类似于上面的函数。我正在尝试查看是否有办法将 initial 输入限制为仅来自 children 数组的列表。

例如,

// should work
navigation({ children: ["one", "two", "three"], initial: "one" })
navigation({ children: ["one", "two", "three"], initial: "two" })

// should throw a type error
// Type 'four' is not assignable to type 'one' | 'two' | 'three'.
navigation({ children: ["one", "two", "three"], initial: "four" })

有没有办法使用 typescript 来做到这一点?

我只能想到在函数中抛出一个错误

function navigation({ children, initial }: INavigation) {
   
  if (!children.includes(initial)) {
    throw new Error(`${initial} is invalid. Must be one of ${children.join(',')}.`
  }
  return null
}

TS Playground

最佳答案

您需要使您的 INavigation 类型通用,以便它可以捕获一些特定的字符串集。

interface INavigation<Children extends readonly string[]> {
  children: Children;
  initial: Children[number];
}

此处 Children 是某种字符串的数组,并被指定为 children 属性的类型。 initial 是该数组的成员类型。

然后使您的函数通用以提供该类型:

function navigation<Children extends readonly string[]>(
  { children, initial }: INavigation<Children>
) {
  return null
}

然后将 as const 添加到您的示例数据中,以确保这些数据被推断为字符串文字类型,而不仅仅是 string

// should work
navigation({ children: ["one", "two", "three"], initial: "one" } as const)
navigation({ children: ["one", "two", "three"], initial: "two" } as const)

// should throw a type error
// Type 'four' is not assignable to type 'one' | 'two' | 'three'.
navigation({ children: ["one", "two", "three"], initial: "four" } as const)

See playground

关于typescript - 根据 typescript 函数中的另一个参数限制一个参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73967239/

相关文章:

reactjs - 使用 react-redux connect 函数时渲染组件出现 Typescript 错误

visual-studio - Visual Studio TypeScript 错误 "Cannot compile modules unless the ' --module' 提供了标志。”

angular - 在 Angular 中导入和使用 lodash 的正确方法

typescript - TypeScript 3 中的项目引用带有单独的 `outDir`

javascript - TypeScript 中的条件类型

typescript - @类型/ react 表 : How to include configured types for users of my package?

node.js - 使用自定义项目环境变量类型减速扩展@types/node

typescript - 如何在 TypeScript 中显式设置 `window` 上的新属性?

javascript - Typescript async/await 与 Observable 或 Promise

typescript - TS2322 : Type 'string | 3000' is not assignable to number