打字稿,方法签名的等价类型?

时间:2017-04-27 13:57:05

标签: typescript

好奇是否有办法确定方法的签名。希望这段代码能够证明这个问题:

err = collection.Find(bson.M{
    "location": bson.M{
        "$geoWithin": bson.M{
            "$centerSphere": []interface{}{
                []interface{}{-73.93414657, 40.82302903}, 5 / 3963.2,
            },
        },
    },
}).All(&cites)

2 个答案:

答案 0 :(得分:1)

您需要认为静态类型仅在设计时可用(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);

答案 1 :(得分:0)

不确定,但你应该试试这个:

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

编辑:它不起作用,但我认为将它存储在变量中是唯一的方法:

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

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