小编oni*_*mk2的帖子

TypeScript 接口有匿名函数和命名函数吗?

我认为接口很少有匿名和命名函数。这是正确的吗?

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)

typescript

4
推荐指数
2
解决办法
3412
查看次数

Typescript类:当我使用两个类时,类会被提升吗?

背景

1.class要提前定义

我知道没有错误,因为类是提前定义的。

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)

2.等级未提升

我也知道这个错误的原因。类没有被提升,所以这个错误是我的预期结果。

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)

javascript typescript

3
推荐指数
1
解决办法
593
查看次数

标签 统计

typescript ×2

javascript ×1