TypeScript Enforce definite initialization of static members

wljmcqd8  于 2个月前  发布在  TypeScript
关注(0)|答案(8)|浏览(36)

TypeScript 3.2.0-dev.20181011

strictPropertyInitialization, static, initialized, uninitialized, assigned, property

代码

class A {
  static s: number
  a() {
    A.s * 3 // Should be a compile error
  }
}
A.s * 7 // Should be an compile error

预期行为:两行都应该产生编译错误。

实际行为:两行都导致运行时异常。

Playground链接

相关问题:

zzzyeukh

zzzyeukh1#

建议我们总是在没有初始化器的静态字段上出错吗?

mxg2im7a

mxg2im7a2#

当我使用一个尚未被确定分配的静态字段时,是否会出现错误?如果这不是一个足够常见的模式来支持,那么你的建议是正确的。对我来说,这两种情况都比当前的行为更安全。
例如:

class A {
  static s: number
}

if (x) {
  A.s = 3
  // OK to read A.s in this branch
}
// NOT OK to read A.s in this branch
yqhsw0fo

yqhsw0fo3#

我也无法想出一个合适的解决方法。有什么建议吗?

ubof19bj

ubof19bj4#

为什么static的属性来自--strictPropertyInitialization?

z9gpfhce

z9gpfhce5#

建议我们总是在没有初始化器的静态字段上出错吗?
对于非静态成员,应适用相同的规则 - 如果类型不允许 undefined ,则属性需要初始化,否则它将具有不允许的值。
@weswigham 你期待什么样的反馈?
我刚刚发现了一个非常愚蠢的错误,这个检查本来可以捕获到:

export class JSONPreprocessorType implements MessagePreprocessorType {
    static contentType: 'application/json';
}

(它应该是一个 = 而不是 : 。)

mctunoxg

mctunoxg6#

我更希望在声明的地方尽早发现错误。通常你无法弄清楚用法(因为它在另一个文件中)。
我最近遇到了与@Yogu相同的问题,并对strictNullChecks没有捕获这个问题感到非常惊讶。

krcsximq

krcsximq7#

我刚刚遇到了一个bug,在类型(:)后面而不是(=)。欢迎修复这个bug。

k5ifujac

k5ifujac8#

自从类静态块在4.4版本中被引入,TypeScript似乎可以使用与示例变量和构造函数相同的启发式方法:

class Foo {
  // Suggested error: Property 'instanceValue' has no initializer and is not definitely assigned in a static block.
  static staticValue: number; 

  // @ts-expect-error "Property 'instanceValue' has no initializer and is not definitely assigned in the constructor.(2564)"
  instanceValue: number;

  static {
    // this.staticValue = 42;
  }

  constructor() {
    // this.instanceValue = 42;
  }
}

相关问题