tom10271
tom10271

Reputation: 4647

How to write a type of string or a function callback in TypeScript?

export interface IBaseFormConfig {
    hints?: string | (Map<string, any>): string;
    validators?: any | (Map<string, any>): any;
}

This is not working. It is a decorator. So developers can decorate an attribute like:

@IBaseFormConfig({
    hints: 'This is the hint'
})

// or

@IBaseFormConfig({
    hints: () => {
        // Developers can resolve its hints dynamically with services.

        return 'This is the hint';
    }
})

How to correctly write the type definition for this interface attribute?

Upvotes: 0

Views: 38

Answers (1)

basarat
basarat

Reputation: 276085

type of string or a function callback in TypeScript?

Simple :

export interface IBaseFormConfig {
  hints?: string | { (arg: Map<string, any>): string };
}

Docs

Its called a callable signature : https://basarat.gitbook.io/typescript/content/docs/types/callable.html

Upvotes: 2

Related Questions