2016-08-12 66 views
1

以下工作:允許對象文本,防止串

class Foo { 
    public bar(param: {}): void { 

    } 
} 

let foo: Foo = new Foo(); 
foo.bar(""); // Ok 
foo.bar({test: ""}); // Also Ok 

是否有可能改變bar方法簽名,以便:

foo.bar({somePropertyWhichIdontKnowTheName: ""}); // Would be ok 
foo.bar(""); // Not Ok 

回答

1

試試這個:

class Foo { 
    public bar(param: { [key: string]: any }): void { 

    } 
} 

或者:

type FooBarParams = { 
    [key: string]: any 
} 

class Foo { 
    public bar(param: FooBarParams): void { 

    } 
} 

然後:

let foo: Foo = new Foo(); 
foo.bar(""); // Error: Argument of type 'string' is not assignable to parameter of type { [key: string]: any } 
foo.bar({test: ""}); // ok 
相關問題