如何为品牌类型制作类型保护

时间:2019-04-05 15:42:20

标签: typescript

这就是我所拥有的

    type Brand<K, T> = K & { __brand: T };

    type USD = Brand<number, 'USD'>;
    type EUR = Brand<number, 'EUR'>;

    const convertToEURO = (value: USD | EUR): EUR => {
        if (isUSD(value)) {
            return (value * 1.2) as EUR;
        }
        return value;
    };

    function isUSD(currency: USD | EUR): currency is USD {
        return '__brand' in currency; // && currency.__brand === 'USD';
    }

    test('Branded number', () => {
        let usd = 5 as USD;
        let eur = 10 as EUR;

        // fails - cool!
        // usd = eur;
        expect(usd).toBe(5);

        expect(eur).toBe(10);

        expect(convertToEURO(usd)).toBe(6);
        expect(convertToEURO(eur)).toBe(10);

        // Compiler shows error because "5" is neither EUR or USD
        expect(convertToEURO(5)).toBe(10);
    });

如果我运行此测试,我将得到Cannot use 'in' operator to search for '__brand' in 5 很清楚为什么,但是我还能如何测试价值是美元还是欧元?

0 个答案:

没有答案