简体   繁体   中英

TypeScript: Define a callable type without CallableFunction properties

Let's declare a type T that has a call signature:

type T = () => number;

Let's also declare a variable t of this type:

declare const t: T;

In the TypeScript Playground or an IDE, we immediately see that t , being of type T , has a great deal of methods and properties that we never declared explicitly: apply , bind , caller , and so on.

How do we declare T so that it's defined only by its call signature? (TS 3.8.3+)

Notably, the type Omit<T, "apply" | "bind" | "caller"> Omit<T, "apply" | "bind" | "caller"> Omit<T, "apply" | "bind" | "caller"> is {} , and so is Omit<T, ""> . Furthermore, Omit<CallableFunction, ""> is not a callable type according to tsc .

For core types (string, number and yes Function), you cannot do it from type declarations.

Creating your own environment

Compile with --noLib and include your own definitions in your someFile.d.ts for interface String , interface Function etc.

The definitions will still apply globally to all string / number / Function etc. For example if you don't include .bind it will not be present for any functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM