Greg Owen
Greg Owen

Reputation: 1177

Exclude a particular type from `any`

I have a function that currently takes an input of type any and logs it:

function foo(input: any): void { // log input }

My project has a particular type that is used for secrets, and I'd like to make sure that foo is never called with an argument of type Secret (but all other types are still ok).

I tried the following:

function foo(input: Exclude<any, Secret>): void { // log input }

but this passes the typecheck even when I call foo on an input of type Secret (here's a Playground link that shows the problem where I'm using string instead of secret).

How can I construct the complement type of Secret?

Upvotes: 0

Views: 388

Answers (1)

Aplet123
Aplet123

Reputation: 35512

You can use a generic, and check if it extends Secret. If it does, then make the parameter type never so typescript errors:

function foo<T>(input: T extends Secret ? never : T): void {
    console.log(input);
}

Playground link..

Upvotes: 2

Related Questions