I’m just playing around with TypeScript and wrote this:
<code>type HTTPChars = 'a' | 'b'
type IsHTTPHost<S extends any, T = S> = S extends HTTPChars
? T
: S extends `${HTTPChars}${infer U}`
? IsHTTPHost<U, T>
: T extends string
? `"${T}" contains illegal characters`
: `Provided value must be a string`;
const hostname1 = 'aaa'
const hostname2 = 'bbb'
const hostname3 = 'something invalid here'
const hostname4 = 9
type cases = [
Expect<Equal<typeof hostname1, IsHTTPHost<typeof hostname1>>>,
Expect<Equal<typeof hostname2, IsHTTPHost<typeof hostname2>>>,
ExpectFalse<Equal<typeof hostname3, IsHTTPHost<typeof hostname3>>>,
Expect<Equal<IsHTTPHost<typeof hostname3>, '"something invalid here" contains illegal characters'>>,
Expect<Equal<IsHTTPHost<typeof hostname4>, 'Provided value must be a string'>>
]
</code>
<code>type HTTPChars = 'a' | 'b'
type IsHTTPHost<S extends any, T = S> = S extends HTTPChars
? T
: S extends `${HTTPChars}${infer U}`
? IsHTTPHost<U, T>
: T extends string
? `"${T}" contains illegal characters`
: `Provided value must be a string`;
const hostname1 = 'aaa'
const hostname2 = 'bbb'
const hostname3 = 'something invalid here'
const hostname4 = 9
type cases = [
Expect<Equal<typeof hostname1, IsHTTPHost<typeof hostname1>>>,
Expect<Equal<typeof hostname2, IsHTTPHost<typeof hostname2>>>,
ExpectFalse<Equal<typeof hostname3, IsHTTPHost<typeof hostname3>>>,
Expect<Equal<IsHTTPHost<typeof hostname3>, '"something invalid here" contains illegal characters'>>,
Expect<Equal<IsHTTPHost<typeof hostname4>, 'Provided value must be a string'>>
]
</code>
type HTTPChars = 'a' | 'b'
type IsHTTPHost<S extends any, T = S> = S extends HTTPChars
? T
: S extends `${HTTPChars}${infer U}`
? IsHTTPHost<U, T>
: T extends string
? `"${T}" contains illegal characters`
: `Provided value must be a string`;
const hostname1 = 'aaa'
const hostname2 = 'bbb'
const hostname3 = 'something invalid here'
const hostname4 = 9
type cases = [
Expect<Equal<typeof hostname1, IsHTTPHost<typeof hostname1>>>,
Expect<Equal<typeof hostname2, IsHTTPHost<typeof hostname2>>>,
ExpectFalse<Equal<typeof hostname3, IsHTTPHost<typeof hostname3>>>,
Expect<Equal<IsHTTPHost<typeof hostname3>, '"something invalid here" contains illegal characters'>>,
Expect<Equal<IsHTTPHost<typeof hostname4>, 'Provided value must be a string'>>
]
Is there any way to derive a type called HTTPHost
based on IsHTTPHost
above, which
becomes the string literal type limited to all sequences of a
and b
?