Typescript TS-如何恢复旧的——非强制性行为

Typescript TS-如何恢复旧的——非强制性行为,typescript,configuration,Typescript,Configuration,有人能告诉我如何归档这种情况吗 let x; 将抛出异常而不发出它?我真的更喜欢2.1之前TS版本的行为。也许TSlint可以解决我的问题?不同之处在于,由于2.1在指定给x时,它将推断实际类型,而不仅仅是使用任何。在您将数字分配给x之前,它可能看起来有类型any,但实际上尝试使用它时,您会发现它以类型undefined开头 它不会显示在单行示例中,但在分配给x之前,只能将其作为未定义的使用,分配给它后,类型会相应地变宽或更改 考虑以下代码: function foo(z: boolean)

有人能告诉我如何归档这种情况吗

let x;

将抛出异常而不发出它?我真的更喜欢2.1之前TS版本的行为。也许TSlint可以解决我的问题?

不同之处在于,由于2.1在指定给
x
时,它将推断实际类型,而不仅仅是使用
任何
。在您将数字分配给
x
之前,它可能看起来有类型
any
,但实际上尝试使用它时,您会发现它以类型
undefined
开头

它不会显示在单行示例中,但在分配给
x
之前,只能将其作为
未定义的
使用,分配给它后,类型会相应地变宽或更改

考虑以下代码:

function foo(z: boolean) {
  let x;
  if (x) {   // Editor sees the type here as `undefined`
    x.foo(); // Error here, the type of `x` is now `never`
  }

  x = 3;     // `x` now has type `number`
  if (z) {
    x = 'foo'; // `x` now has type `string`
  }
  let y = x;   // Both `x` and `y` now have type `string|number`
  console.log(y.toFixed()); // Error, `toFixed` does not exist on `string|number`
}
将定义更改为
let x:any
而此代码将毫无怨言地编译,因为这里的
x
类型实际上是
any

function foo(z: boolean) {
  let x: any;

  x = 3;
  if (z) {
    x = 'foo';
  }
  let y = x;
  console.log(y.toFixed()); 
}
y
的类型显式为
any
,因为它是从
x
的类型推断出来的

回到你的一行:

let x;
这不是隐式的
any
,因为推断的类型是
undefined


要回答这个问题,不,您不能关闭类型推断。

不同之处在于,自2.1以来,当您分配给
x
时,它将推断实际类型,而不仅仅是使用
任何
。在您将数字分配给
x
之前,它可能看起来有类型
any
,但实际上尝试使用它时,您会发现它以类型
undefined
开头

它不会显示在单行示例中,但在分配给
x
之前,只能将其作为
未定义的
使用,分配给它后,类型会相应地变宽或更改

考虑以下代码:

function foo(z: boolean) {
  let x;
  if (x) {   // Editor sees the type here as `undefined`
    x.foo(); // Error here, the type of `x` is now `never`
  }

  x = 3;     // `x` now has type `number`
  if (z) {
    x = 'foo'; // `x` now has type `string`
  }
  let y = x;   // Both `x` and `y` now have type `string|number`
  console.log(y.toFixed()); // Error, `toFixed` does not exist on `string|number`
}
将定义更改为
let x:any
而此代码将毫无怨言地编译,因为这里的
x
类型实际上是
any

function foo(z: boolean) {
  let x: any;

  x = 3;
  if (z) {
    x = 'foo';
  }
  let y = x;
  console.log(y.toFixed()); 
}
y
的类型显式为
any
,因为它是从
x
的类型推断出来的

回到你的一行:

let x;
这不是隐式的
any
,因为推断的类型是
undefined


回答这个问题,不,你不能关闭类型推断。

谢谢。特别是你的最后一句话对我帮助很大:)。但我必须有点固执。难道并没有办法通过使用TSLint或类似的东西来进行类型推断吗?提前谢谢:)谢谢。特别是你的最后一句话对我帮助很大:)。但我必须有点固执。难道并没有办法通过使用TSLint或类似的东西来进行类型推断吗?提前感谢:)