typescript

TS2322: Type string | number | boolean | Dayjs is not assignable to type never


I have this Code:

function changeKurs(what: keyof typeof kurs, newValue: string | number | boolean | Dayjs){
    const tmpKurs = cloneDeep( kurs );
    if (Object.prototype.hasOwnProperty.call(tmpKurs, what)) {
        tmpKurs[what] = newValue;
        setkurs(tmpKurs);
    }else {
        console.error(`Property '${what}' does not exist in kurs`);
    }
}

On this line tmpKurs[what] = newValue; I get the error message TS2322: Type string | number | boolean | Dayjs is not assignable to type never and I do not understand this error message.

Can somebody pls explain it to me / fix it for me. Thanks


Solution

  • First you should link the property's key and value, there's no sense to assign a number to a string for example.

    Second, your cloneDeep should be an identity function, otherwise cast as as typeof kurs:

    Playground

    const cloneDeep = <T extends object>(obj: T) => obj;
    
    const kurs = {
        value: 'value',
        value2: 1
    }
    
    type Kurs = typeof kurs;
    
    function changeKurs<K extends keyof Kurs>(what: K, newValue: Kurs[K]){
        const tmpKurs = cloneDeep( kurs ); // add "as Kurs" if doesn't work
        if (Object.prototype.hasOwnProperty.call(tmpKurs, what)) {
            tmpKurs[what] = newValue;
            setkurs(tmpKurs);
        }else {
            console.error(`Property '${what.toString()}' does not exist in kurs`);
        }
    }
    
    changeKurs('value', 'value2');
    changeKurs('value', 1); // error, wrong type