admin管理员组

文章数量:1291108

Let's start simple.

I can do this in TypeScript to have a "kind of" Not type:

type Not<S extends string> = Exclude<S, 'not'>

Next, let's test it:

type T1 = Not<'not'>; // => never

Works fine.

Now, I want to use it in a function:

function f<S extends string>(s: Not<S>) {}

f('not'); // => Error! 

Perfect.

Now, onto the problem.

I want to make it work without generics:

function f(s: Not<string>) {}

f('not'); // => No Error :( 

That obviously doesn't work.

For my use case, it's even worse, as I want to extract the argument directly:

type FstArg<T> = T extends (a: infer A) => any ? A : never;

type Arg = FstArg<typeof f> // => string

I wish Arg would be something like Exclude<X?, 'not'>.

I do understand why this doesn't work, but is there a workaround for this?

This would probably require a true Not type, I guess?

Playground

本文标签: typescriptPreserving Exclude in Argument ExtractionStack Overflow