Typescript从同一接口支柱创建动力联合类型

发布于 2025-02-07 06:49:31 字数 438 浏览 2 评论 0原文

我想从同一界面的兄弟创建联合类型,

如下


interface Foo {
  values: string[];
  defaultValue: string;
}

function fooo({values, defaultValue}: Foo) {}

fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example

fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'

所示吗?

I want to create union type from brother of same interface

like below


interface Foo {
  values: string[];
  defaultValue: string;
}

function fooo({values, defaultValue}: Foo) {}

fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example

fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'

Can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温暖的光 2025-02-14 06:49:31

当然,您可以通过添加通用类型来实现这一目标。

interface Foo<K extends string[]> {
  values: [...K];
  defaultValue: K[number];
}

function fooo<K extends string[]>({values, defaultValue}: Foo<K>) {}

通用类型kvalue数组的元组类型。然后,我们将defaultValue限制为仅在values中指定的值 k [number]

让我们看看它是否有效:

fooo({values: ['a', 'b'], defaultValue: 'a'});
fooo({values: ['a', 'b'], defaultValue: 'c'}); // error: Type '"c"' is not assignable to type '"a" | "b"'

游乐场

Sure, you can achieve this by adding generic types.

interface Foo<K extends string[]> {
  values: [...K];
  defaultValue: K[number];
}

function fooo<K extends string[]>({values, defaultValue}: Foo<K>) {}

The generic type K will the tuple type of the value array. We then constrain defaultValue to only have the values specified in values with K[number].

Let's see if it works:

fooo({values: ['a', 'b'], defaultValue: 'a'});
fooo({values: ['a', 'b'], defaultValue: 'c'}); // error: Type '"c"' is not assignable to type '"a" | "b"'

Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文