是否可以根据其值类型来动态更改变量类型?

时间:2019-08-22 03:02:45

标签: typescript

我想使用一个typescript变量,允许根据其值假定不同的类型,并进行类型检查(因此我需要避免使用“ any”)。

例如:

class Car
{
    public string LicensePlate;
}
class Driver
{
    public string Name;
}

function GetCar(licensePlate: string): Car { ... }
function GetDriver(name: string): Driver { ... }

let licensePlate: string;
let name: string;

let result = GetCar("123");
licensePlate = result.LicensePlate;

result = GetDriver("Bob");
name = result.Name;

基本上,我需要“重用”具有不同类型值的变量,以进行类型检查。

打字稿可以允许吗?

谢谢

2 个答案:

答案 0 :(得分:1)

只要您不进行任何类型的初始化,就可以将其转换
只需声明没有类型的变量即可,例如let test1

class A {
  val1: string
}
class B {
  val2: number
}

// OK
let test1
test1 = new A()
console.log('test1', (test1 as A).val1) // requires type cast
test1 = new B()
console.log('test1', (test1 as B).val2) // requires type cast

// Error
let test2 = new A()
console.log('test2', test2.val1)        // dont need type cast
test2 = new B()                         // Property 'val1' is missing in type 'B' but required in type 'A'
console.log('test2', test2.val2)        // Property 'val2' does not exist on type 'A'
console.log('test2', (test2 as B).val2) // Conversion of type 'A' to type 'B' may be a mistake because neither type sufficiently overlaps with the other

答案 1 :(得分:0)

我找到了解决方法:

  1. 将Typescript版本更新为3.5.3
  2. 设置noImplicitAny标志

现在我可以做:

let result; //Here result type is any   
result = new A(); //Here result type is A   
result = new B(); //Here result type is B   

智能感知和类型检查就像基于变量赋值的魅力一样工作