I would like to create a TypeScript type which is checking if an element COULD be a string or not.
That means that this element could have the type "string" or "any", but not "number", "boolean", "number[]", "Person", etc.
I tried with conditional types, but I can't find how to exclude "all which is impossible to be a string".
I tried too the type Exclude<any, string>, but that's not exactly what I want.
EDIT
I explain better my problem : I create a static method foo(data) which will do something and return a string if data is a string or do something else and return a number if data is not a string.
For that, it's simple, I can do an overload 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, assume that the foo() method will throw an Error if data is not a string. I have two cases :
If the user of the method don't know the type of the data (which could be a
string), I want that he can use this method and I will return an Error if it's not astring.If the user knows the type of the data (a
number, for example), I want to tell him that it's impossible, it can't be astring. I want to tell that on type checking (error displayed 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'd like to know how to define the type NotAString (or its contrary, CouldBeAString).
Any idea ?
Thanks !
anybut not "number", "boolean", "number[]", "Person", etc? Do you understand the meaning ofany? Wwhat is "etc."? You need either a complete whitelist or a complete blacklist but it looks like you have neither. The whitelist "string" or "any" means that all types are allowed.