我认为接口很少有匿名和命名函数。这是正确的吗?
TypeScript 编译器允许接口同时具有匿名和命名函数。
// no error
interface Foo {
(x: number, y: number): number; // anonymous
namedMethod: (z: string, w: string) => string; // named
}
Run Code Online (Sandbox Code Playgroud)
但是好像不能用。
// badProp is not assignable
const foo1 : Foo = {
badProp(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; }
}
// syntax error
const foo2 : Foo = {
(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; } …Run Code Online (Sandbox Code Playgroud) 我知道没有错误,因为类是提前定义的。
class Polygon {
log() { console.log('i am polygon'); }
}
const p = new Polygon(); // no error as I had expected.
p.log();
Run Code Online (Sandbox Code Playgroud)
我也知道这个错误的原因。类没有被提升,所以这个错误是我的预期结果。
const b = new Bolygon(); // Uncaught TypeError as I had expected.
b.log();
class Bolygon {
log() { console.log('i am bolygon'); }
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,例如这段代码(playground link),类会被提升吗?
我不明白为什么new Hero()不会导致下面的错误。
class Hero被吊起?
class AppComponent {
hero = new Hero('foo') // why no error?
}
class Hero {
constructor(public name: …Run Code Online (Sandbox Code Playgroud)