打字稿:如何对复杂类型进行类型检查?

时间:2018-06-21 16:45:45

标签: typescript typechecking

我有一些复杂的类型:

type odds: 1 | 3 | 5 | 7 | 9;
type evens: 2 | 4 | 6 | 8 | 0

...以及一些采用这些复杂类型的函数:

function(digit: odds | evens) { ... }

我想检查我得到的是哪种类型,但以下任何一项都不起作用:

if (digit isntanceof odds) // error: odds refers to a type but is being used as a value
if (typeof digit === ???) // issue: no single value for typeof

如何使用类型检查数字是否为奇数?

2 个答案:

答案 0 :(得分:3)

类型在编译器时不存在,因此typeof不起作用,您需要某种其他类型的检查来在运行时测试类型。 Typescript使用custom type-guards

对此提供了支持
type odds = 1 | 3 | 5 | 7 | 9;
type evens = 2 | 4 | 6 | 8 | 0;
function isOdd(v: odds | evens) : v is odds {
    return v % 2 != 0
}

declare let n: odds | evens;
withEven(n) // invalid here no check has been performed
withOdd(n) // invalid here no check has been performed
if (isOdd(n)) {
    n // is typed as odd
    withEven(n) // invalid here
    withOdd(n) // valid here we checked it is odd
} else {
    n // is typed as even
    withEven(n) // valid here we checked it is not odd
    withOdd(n) // invalid here
}
function withEven(n: evens) { }
function withOdd(n: odds) { }

答案 1 :(得分:-1)

@SephReed TS中的联合类型提供了一种检查属性的方法。您可以创建类型,然后检查类型属性。请使用联合http://www.typescriptlang.org/docs/handbook/advanced-types.html

检查预付款类型
interface Evens {
evenProp:number;

}

interface Odds {
oddProp:number;

}

class AdvanceUnionType{
check = function(digit: Odds | Evens) {
    if ((<Odds>digit).oddProp){
        console.log("Odd object passed");
    }else if((<Evens>digit).evenProp){
        console.log("Even object passed");
    }
}

}

(function(){
'use strict';

let even:Evens = {evenProp: 10};
let odd:Odds = {oddProp: 9};
let advanceType = new AdvanceUnionType();
advanceType.check(even);
advanceType.check(odd);

}());