Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a property as string or function that returns a string in Typescript

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?

like image 603
Sebastian Sebald Avatar asked Oct 29 '15 08:10

Sebastian Sebald


People also ask

How do I create a return type function in TypeScript?

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.

What is return type in TypeScript?

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.


1 Answers

type propType = () => string;

interface IExample {
   field : string | propType;
}

class MyClass1 implements IExample {
    field : string;
}

class MyClass2 implements IExample {
    field() {
        return "";
    }
}

Update 1

type PropertyFunction<T> = () => T;

interface IExample {
   field : string | PropertyFunction<string>;
}
like image 175
TSV Avatar answered Nov 02 '22 23:11

TSV