【问题标题】:issue with typing an object Typescript error - no index signature键入对象 Typescript 错误的问题 - 没有索引签名
【发布时间】:2019-01-03 18:15:38
【问题描述】:

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

元素隐式具有“任何”类型,因为 type '{ 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}</>;
};

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案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 ? */ }
    };
    

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2018-02-23
      • 2017-05-11
      • 2017-06-11
      • 2019-11-23
      • 2018-06-16
      相关资源
      最近更新 更多