typescriptdeclarationtsd

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?


Solution

  • 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>;
    }