如何限制通用接口在打字稿中接受特定数据类型?

发布于 2025-01-24 07:28:56 字数 489 浏览 3 评论 0 原文

如何限制通用接口在打字稿中接受特定数据类型?

我知道,在typescript中的通用接口中定义哪些数据类型可以接受。

interface exampleInterface<T = void | any>;

但是,如果我想限制接口接受一种或两种特定的数据类型怎么办?

注意: 我已经查看了以下问题,应该提到它与我的问题相反,因为它谈论了如何定义哪些数据类型是可以接受的,而我试图在此通用界面中定义哪些数据类型是不可接受的。

将通用类型限制在类型

How do I restrict a generic interface from accepting a specific data type in typescript?

I know that to define what data types are acceptable to be passed in a generic interface in typescript.

interface exampleInterface<T = void | any>;

but what if I want restrict my interface from accepting one or two specific data types?

Note:
I have already viewed the following question and should mention that it is opposite of my question as it talks about how to define what data types ARE acceptable while I am trying to define what data types ARE NOT acceptable to be passed in this generic interface.

Restricting generic types to one of several classes in Typescript

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

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

发布评论

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

评论(1

苦行僧 2025-01-31 07:28:56

这样做的一种方法是定义 type 这样的方法:

type NotAcceptable<T> = T extends string | undefined ? never : T

在这种情况下,不允许使用字符串 undefined

然后,您可以这样使用它:

let t1: NotAcceptable<string> = "abc"  // Error

function test<T>(t: NotAcceptable<T>){}

test("string")  // Error
test(undefined) // Error
test(123)       // Ok

唯一的缺点是类型,而不是问题中指定的接口。但是,您始终可以使用界面和例如添加道具之类的类型:

type NotAcceptable<T> = T extends string | undefined ? never : {
  abc: T
}

Playground

One way to do this would be to define a type like this:

type NotAcceptable<T> = T extends string | undefined ? never : T

In this case string and undefined wouldn't be allowed.

You could then use it like this:

let t1: NotAcceptable<string> = "abc"  // Error

function test<T>(t: NotAcceptable<T>){}

test("string")  // Error
test(undefined) // Error
test(123)       // Ok

The only downside to this is this being a type and not an interface as you specified in your question. But you can always use types like an interface and e.g. add props:

type NotAcceptable<T> = T extends string | undefined ? never : {
  abc: T
}

Playground

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