键入对象Typescript错误的问题-没有索引签名

时间:2019-01-03 09:51:19

标签: javascript reactjs typescript

我有一个需要输入的对象,但是不确定如何执行此操作。 以下是我看到的错误,下面是我的代码。

  

元素隐式地具有“ any”类型,因为类型为'{LIV:string;男子:   串; LDN:字符串; }'没有索引签名。 [7017]

type Props = {
    city: string;
    cityMap: {
        LIV: string;
        MAN: string;
        LDN: string;
    };
};

const Cities = ({ city }: Props) => {
    const cityMap = {
        LIV: 'Liverpool',
        MAN: 'Manchester',
        LDN: 'London'
    };

    const city = cityMap[city];
    return <>{city}</>;
};

1 个答案:

答案 0 :(得分:1)

使用noImplictAny打字稿不会让您索引具有任意字符串的对象(因为这实际上不是类型安全的,并且这样的索引操作的结果将隐式为any

有几种可能的解决方案。

city的类型更改为keyof Props['currencyMap']

type Props = {
    city: keyof Props['currencyMap'];
    currencyMap: {
        LIV: string;
        MAN: string;
        LDN: string;
    };
};

const Cities = ({ city }: Props) => {
    const cityMap = {
        LIV: 'Liverpool',
        MAN: 'Manchester',
        LDN: 'London'
    };

    const cityName = cityMap[city];
};.

或者使用类型断言来告诉编译器您确定city将是适当的密钥:

const Cities = ({ city }: Props) => {
    const cityMap = {
        LIV: 'Liverpool',
        MAN: 'Manchester',
        LDN: 'London'
    };

    const cityName = cityMap[city as keyof Props['currencyMap']];
};

或者您可以使用检查来确保city是带有自定义类型防护的预期键:

const Cities = ({ city }: Props) => {
    const cityMap = {
        LIV: 'Liverpool',
        MAN: 'Manchester',
        LDN: 'London'
    };
    const isCity = (c: string): c is keyof Props['currencyMap'] => c in cityMap; 
    if (isCity(city)) {
        cityMap[city];
    }else { /* What now ? error ? */ }
};