TypeScript type for any string other than a specific string literal

Viewed 401

Is it possible creating a type for any string other than a specific string literal?

type FooString = 'foo' | string

type Foo = 'foo'

type NotFoo = ?

Goal:

const a: NotFoo = 'foo'; // error

const b: NotFoo = 'bar'; // ok

1 Answers

Conditional type will make a trick:

type FooString = 'foo' | string

type Foo = 'foo'
type NotFoo<T extends string> = T extends 'foo' ? never : T

const notFoo = <T extends string>(arg: NotFoo<T>):T => arg

const result = notFoo('hello') // ok
const result2 = notFoo('foo') // error

type Result = NotFoo<'foo'> // never
type Result2 = NotFoo<'bar'> // 'bar'

Playground link

If arg is foo, NotFoo util will return never type. never type is not something you can provide as an argument.

Related