2

I'am learning typescript and i don't know how to solve this.

My goal is to find a key: string in some random text and replace it with the 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;
    }
}

Type 'string' is not assignable to type '{ value: string; }'. The expected type comes from this index signature.

1 Answer 1

3

Short Answer

You either need this...

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

... or you need this.

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
};

Note that an index type's value does not need the value keyword.

Here are two more examples. The ObjectValues type is what you did; the StringValues type might be what you want.

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',
}

Here is your example in the playground and also here in the playground with the two approaches.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.