很好奇是否有办法确定方法的签名。希望这段代码能说明这个问题:
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'
Run Code Online (Sandbox Code Playgroud)
您需要考虑静态类型仅在设计时(TypeScript)可用,而不在运行时(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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1867 次 |
| 最近记录: |