【问题标题】:Type 'string' is not assignable to type '{ value: string; }'类型 'string' 不可分配给类型 '{ value: string; }'
【发布时间】:2019-11-15 14:51:39
【问题描述】:

我正在学习打字稿,但我不知道如何解决这个问题。

我的目标是在一些随机文本中找到一个 key: string 并将其替换为 value: string。

export class Smiley {
    private smiley: {[key: string]: {value: string}} = {
        ':-)': '°>sm_00...b.pw_18.ph_18.gif<°',
        ':-(': '°>sm_03...b.pw_18.ph_18.gif<°',
        ':-|': '°>sm_13...b.pw_18.ph_18.gif<°',
        ':-D': '°>sm_10...b.pw_18.ph_18.gif<°',
        ':-O': '°>sm_06...b.pw_18.ph_18.gif<°',
    };
    tbsmiley(str: string): string {
        const obj = this.smiley;
        Object.keys(obj).forEach((key) => {
            const ind = str.indexOf(key);
            if ( ind >= 0 ) {
                str = str.substring(0, ind) + obj[key] + str.substr(ind + key.length);
                return str;
            }
        });
        return str;
    }
}

类型 'string' 不能分配给类型 '{ value: string; }'。 预期类型来自此索引签名。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    简答

    你要么需要这个......

    private smiley: {[key: string]: string } = { // <--- changed type
      ':-)': '°>sm_00...b.pw_18.ph_18.gif<°',
      ':-(': '°>sm_03...b.pw_18.ph_18.gif<°',
    };
    

    ...或者你需要这个。

    private smiley: {[key: string]: { value: string } } = { 
      ':-)': { value: '°>sm_00...b.pw_18.ph_18.gif<°' }, // <-- changed values
      ':-(': { value: '°>sm_03...b.pw_18.ph_18.gif<°' }, // <-- changed values
    };
    

    请注意,index type's 值不需要 value 关键字。

    这里还有两个例子。 ObjectValues 类型就是你所做的; StringValues 类型可能是您想要的。

    type ObjectValues = {
        [key: string]: { value: string }
    }
    
    const objectValues: ObjectValues = {
      'someKey1': { value: 'someValue1' },
      'someKey2': { value: 'someValue2' }
    }
    
    type StringValues = {
        [key: string]: string;
    }
    
    const stringValues: ObjectValues = {
      'someKey1': 'someValue1',
      'someKey2': 'someValue2',
    }
    

    这是您的示例 in the playgroundalso here in the playground 使用这两种方法。

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2019-05-12
      相关资源
      最近更新 更多