TypeScript `Object.defineProperty` 无法在 'this' 上定义属性,

hjqgdpho  于 4个月前  发布在  TypeScript
关注(0)|答案(7)|浏览(54)

预期结果:无错误。
实际结果:Property 'x' does not exist on type 'C'.

at0kjp5o

at0kjp5o1#

Unfortunately it doesn't work in TS as well,
if you run this in TS playground (I guess it has the latest TS version)

let obj = {};
Object.defineProperty(obj, "x", { value: "hello", writable: false });

obj.x.toLowercase();

then it will show only one error message:
"Property 'x' does not exist on type '{}'"
but I expected to get different error like "Property 'toLowercase' does not exist on type 'string'" as was described in https://devblogs.microsoft.com/typescript/announcing-typescript-3-2/#objectdefineproperty-declarations-in-javascript

uhry853o

uhry853o3#

这是关于JavaScript分析的,而不是TypeScript。

voj3qocg

voj3qocg4#

我遇到了这个问题。有人知道解决方法吗?

chhkpiq4

chhkpiq45#

n/m,上述问题的解决方法如下:

// @ts-check

class C {
  constructor() {
    /** @type {Readonly<string>} */
    this.x = undefined;
    Object.defineProperty(this, "x", { value: "hello" });

    this.x.toLowerCase();
  }
}
smdnsysy

smdnsysy6#

你需要为属性 'x: string' 添加确定性Assert赋值。

1zmg4dgp

1zmg4dgp7#

我认为在这个问题中,源代码被假定为JavaScript,而且据我所知,没有明确的赋值Assert语法。

相关问题