我正在尝试确定为什么 TypeScript 允许您在实现接口(interface)时将函数的返回类型从更具体的类型重载为“任何”类型。
在我的例子中,我正在使用 Angular 并注入(inject)已实现的类。
我的环境:
Visual Studio 2017
Angular 版本 1.5.5
typescript 版本 2.1.5
下面的代码编译没有任何问题:
export interface IFoo {
thing: (parameter: number) => string;
}
export class BarService implements IFoo {
public thing = (parameter: number): any => {
return { "whatever": parameter };
}
}
angular.module("FooBar").service("barService", BarService);
所以现在当我尝试使用 IFoo 接口(interface)并期望从“thing”函数调用返回一个字符串时,编译器实际上允许它发生!
export class Whatever {
public foo: IFoo;
public myString: string;
static $inject = ["barService"];
constructor(barService: IFoo) {
this.foo = barService;
this.myString = this.foo.thing(0);
}
}
当返回类型重载类型为“any”时,似乎 TypeScript 应该无法编译,因为接口(interface)的使用者需要一个强类型对象。
最佳答案
这是我整理的。
来自 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.1 :
All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints.
还有:
The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.
玩转:
interface IPerson {
name: string
}
class Person implements IPerson {
name: any;
}
// Error
//class Person2 implements IPerson {
// name: number;
//}
const person: Person = new Person();
person.name = 3;
let x: number = 3;
x = <any>"hello"; // Works!
//x = "hello"; // Error
我们甚至可以在上面的一个简单示例中看到,any 可用于覆盖文档后面的类型系统。
我相信这种行为是为了让 javascript 的非类型化(灵活)行为具有灵 active 。
关于angularjs - 为什么 TypeScript 在实现接口(interface)时允许将返回类型重载为 'any',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986327/