I want to create an interface where a property can be either a string
or a Function
that has to return a string
. I currently have the following:
interface IExample {
prop: string|Function;
}
But that's not explicit enough for me because the Function
is allowed to return anything. I want to tell the compiler that the return value has to be a string
.
How is this possible in TypeScript? Or is it possible at all?
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.
type propType = () => string;
interface IExample {
field : string | propType;
}
class MyClass1 implements IExample {
field : string;
}
class MyClass2 implements IExample {
field() {
return "";
}
}
type PropertyFunction<T> = () => T;
interface IExample {
field : string | PropertyFunction<string>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With