This is not possible.
A string in typescript can either be a constant literal string, for example:
const a = "A"
Or it may be of type string which means it may have any content, for example:
const str = prompt("What is your name?")`
There is no way to define a string type that matches any sort of pattern.
I don't know what you are trying to do, but there's probably a better way to design your API here.
If you do know all possibilities, you can treat them like constant strings.
type Bang = "!A" | "!B" | "!C"
type Question = "?A" | "?B" | "?C"
function doStuff(str: Bang): boolean
function doStuff(str: Question): string[]
function doStuff(str: Bang | Question): boolean | string[] {
if (str.startsWith("!")) {
return true
} else {
return ['strings', 'here']
}
}
doStuff('!A') // boolean
doStuff('?A') // string[]
Playground
Update for Typescript 4.1:
Typescript 4.1 (just released in beta on Sept 18, 2020) includes support for Template Literal Types. This lets you have the contents of string literals be strongly typed. You can now pull parts of string literals out and use them on their own.
With this feature, your problem could be solved like so:
// Typescript 4.1
function doStuff<
Prefix extends '!',
Suffix extends string
>(str: `${Prefix}${Suffix}`): boolean
function doStuff<
Prefix extends '?',
Suffix extends string
>(str: `${Prefix}${Suffix}`): string[]
function doStuff<
Prefix extends '!' | '?',
Suffix extends string
>(str: `${Prefix}${Suffix}`): boolean | string[] {
if (str.startsWith("!")) {
return true
} else {
return ['strings', 'here']
}
}
doStuff('!A') // boolean
doStuff('?A') // string[]
doStuff('bad format') // type error
4.1 Playground