为什么TypeScript不对符号属性使用类型缩小?

问题描述 投票:1回答:1

TypeScript似乎不会缩小符号属性的类型。例如:

const bar = Symbol('bar');

class Foo {
    [bar]: string | undefined;
    'baz': string | undefined;
}

function getBarLength(f: Foo) {
    if (f[bar] === undefined) {
        throw new Error('Expected bar to be defined');
    }
    return f[bar].length; // ERROR(2532): Object is possibly undefined
}

function getBazLength(f: Foo) {
    if (f['baz'] === undefined) {
        throw new Error('Expected baz to be defined');
    }
    return f['baz'].length; // No error
}

In the playground

我想知道这是否是设计使然?如果是这样,原因何在?

typescript
1个回答
0
投票

我相信这是您必须使用变量来保留符号值并因此必须使用该变量来访问符号属性(而不是直接访问属性名称)的副作用,例如,它遇到了类似的困难使用对象属性符号时使用字符串属性,即使字符串为const

const abc = 'abc' as const;

class Foo {
    [abc]: string | undefined;
}

function getAbcLength(f: Foo) {
    if (f[abc] === undefined) {
        throw new Error('Expected abc to be defined');
    }
    return f[abc].length; // ERROR(2532): Object is possibly undefined
}

Playground Link

您可以通过将要测试的值分配给一个临时变量来解决此问题,然后对该变量执行类型限制,而不是直接访问该属性两次:]

const bar = Symbol('bar');

class Foo {
    [bar]: string | undefined;
}

function getBarLength(f: Foo) {
    const prop = f[bar];
    if (prop === undefined) {
        throw new Error('Expected bar to be defined');
    }
    return prop.length; // No error
}

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.