typescript 接口函数和只读属性[已关闭]

8yoxcaq7  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(162)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

7天前关闭
截至7天前,社区正在审查是否重新讨论这个问题。
Improve this question
我读了用TypeScript写的新代码,发现了一些我不理解的东西。

interface test {
  (a: number): number;
  readonly b: number;
}

我知道(a:number): number是一个函数,参数是a:number,返回值是number,但我不知道readonly b: number在这段代码中是什么意思。
我测试了底层代码,但它不匹配。

const c: test = (a) => {
  this.b = 1
  return a
};
xt0899hw

xt0899hw1#

您可以使用不同的类型来创建函数并更改类型:

interface test {
  (a: number): number;
  readonly b: number;
}

interface test2 {
  (a: number): number;
  b: number;
}

let c = (function (this: test2, a: number) { this.b = 1; return a; }) as test;

不能在代码中使用箭头函数。箭头函数不捕获this。如果你想使用箭头函数,你必须分两步完成:

interface test {
  (a: number): number;
  readonly b: number;
}

interface test2 {
  (a: number): number;
  b: number;
}

let c = ((a: number) => { return a; }) as test2;
c.b = 1;
let d: test = c;

相关问题