I am looking to create a TypeScript type that can identify whether an element has the potential to be a string.
This means the element should have the type "string" or "any", but not "number", "boolean", "number[]", "Person", etc.
I have experimented with conditional types, but I am struggling to exclude "anything that cannot be a string".
I also tried using the type Exclude
EDIT
Let me explain my problem more clearly: I am creating a static method foo(data)
which will perform a certain action and return a string
if the data is a string
, or do something else and return a number
if the data is not a string
.
To achieve this, I can simply use overloads like this:
class FooClass {
static foo(data: string): string
static foo(data: any): number
static foo(data: any): string | number {
if (typeof data === 'string') {
return 'a';
} else {
return 2;
}
}
}
Now, let's consider that the foo()
method will throw an Error if the data
is not a string
. In this case, there are two scenarios:
If the user of the method does not know the type of the data (which could be a
string
), I want them to be able to use the method and I will return an Error if it's not astring
.If the user knows the type of the data (e.g., a
number
), I want to inform them that it is impossible for it to be astring
. I want this information to be displayed as an error during type checking in the IDE, not at runtime.
class FooClass {
static foo(data: string): string
static foo(data: NotAString): Error
static foo(data: any): string | Error {
if (typeof data === 'string') {
return 'a';
} else {
return new Error();
}
}
}
let foo1: string;
const bar1: string = FooClass.foo(foo1); // No error
let foo2: any;
const bar2: string = FooClass.foo(foo2); // No error
let foo3: number;
const bar3: string = FooClass.foo(foo3); // Error (displayed on the IDE)
let foo4: Bar;
const bar4: string = FooClass.foo(foo4); // Error (displayed on the IDE)
I am interested in knowing how to define the type NotAString (or its opposite, CouldBeAString).
Any suggestions?
Thank you!