0

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

Hassam Ullah
  • 79
  • 1
  • 10
  • Does this answer your question? [Restricting generic types to one of several classes in Typescript](https://stackoverflow.com/questions/48539710/restricting-generic-types-to-one-of-several-classes-in-typescript) – Tobias S. Apr 26 '22 at 20:43
  • @TobiasS. unfortunately no, because my question is about the opposite of this given solution, I want to be able to define what data types ARE NOT acceptable while in this given solution it is described how to to define what data types ARE acceptable – Hassam Ullah Apr 26 '22 at 20:50

1 Answers1

1

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

Tobias S.
  • 21,159
  • 4
  • 27
  • 45