ZackDeRose
ZackDeRose

Reputation: 2256

Typescript, typeof equivalent for method signatures?

Was curious if there is a way to determine a method's signature. Hopefully this code demonstrates the question:

class MyClass {
    constructor(public foo: any){}
}

const object1 = new MyClass((): void => {
    console.log('My function is to say hi. Hello!');
});
const object2 = new MyClass((n: number): void => {
    console.log('My function is echo a number. Here it is: ' + n);
});

object1.foo();      // My function is to say hi. Hello!
object2.foo(15);    // My function is echo a number. Here it is: 15

console.log(typeof object1.foo); // prints 'function'. 
                                 // I'm looking for something that prints '(): void' 
                                 // [or something comparable]

console.log(typeof object2.foo); // prints 'function'. 
                                 // I'm looking for something that prints '(number): void'

Upvotes: 5

Views: 1992

Answers (2)

Antoine Laborderie
Antoine Laborderie

Reputation: 141

Not sure about it, but you should try this:

console.log(typeof var foo1 = object1.foo());
console.log(typeof var foo2 = object2.foo(15));

EDIT: It does not work, but I think storing it in a variable is the only way:

var foo1 = object1.foo();
var foo2 = object2.foo(15);

console.log(typeof foo1);
console.log(typeof foo2);

Upvotes: 0

Remo H. Jansen
Remo H. Jansen

Reputation: 25019

You need to think that static types are only available at design-time (TypeScript) not at runtime (JavaScript):

class MyClass<T> {
    constructor(public foo: T){}
}

const sayHello = (): void => {
    console.log('My function is to say hi. Hello!');
};

const sayANumber = (n: number): void => {
    console.log('My function is echo a number. Here it is: ' + n);
};

const object1 = new MyClass(sayHello);

const object2 = new MyClass(sayANumber);

object1.foo();      // My function is to say hi. Hello!
object2.foo(15);    // My function is echo a number. Here it is: 15

// You can get the design-time types
type designtimeTypeOfFoo1 = typeof object1.foo; // () => void
type designtimeTypeOfFoo2 = typeof object2.foo; // (n: number) => number

// At run-time all the static type information is gone
const runtimeTypeOfFoo1 = typeof object1.foo; // "Function"
const runtimeTypeOfFoo2 = typeof object2.foo; // "Function"

// Error: design-time types are not available ar run-time
console.log(designtimeTypeOfFoo1, designtimeTypeOfFoo2);

// Success: run-time types are available at run-time
console.log(runtimeTypeOfFoo1, runtimeTypeOfFoo2);

Upvotes: 1

Related Questions