TS2345: Argument of type 'string' is not assignable to parameter of type 'never'

Viewed 3976

I have the following Angular service

import { Injectable } from '@angular/core'

import { DictUnit } from '@activejs/core'

@Injectable({
    providedIn: 'root',
})
export class RegistrationState {
    private _dictionaryUnit = new DictUnit({
        id: 'registration',
        immutable: true,
        persistent: true,
        cacheSize: 200,
        // initialValue: {},
        distinctDispatchCheck: true,
    })

    get dictUnit() {
        return this._dictionaryUnit
    }
}

I inject the service into my component:

export class AgeComponent {
    age: IAge = new Age()
    
    constructor(private regState: RegistrationState) {
    }

    onDobValueChanged(e: any) {
        const dob = dayjs(e.value).toDate()
        const years = dayjs().diff(dob, 'year')


        // TS2345: Argument of type 'string' is not assignable to parameter of type 'never' - ERROR REFERES TO 'age' param
        this.regState.dictUnit.set('age', this.age) 
    }

    onDodValueChanged(e: any) {
        this.age.dod = dayjs(e.value).toDate()
        console.log({ dod: this.age.dod })
    }
}

The API for the set function is at https://api.activejs.dev/classes/dictunit.html#set

Why am I getting this result?

I am using the following #1 "typescript": "~4.1.5" - strict mode #2 "@angular/cli": "^11.2.12", #3 Linux Mint Ulyana

Thanks

1 Answers

There is a need to inform DictUnit what data type it is storing explicitly. If nothing specified, it will use Record<never, never>.

Therefore, when setting age in your component class, it will warn you the type is incompatible (string != never).

A simple fix will be like that:

private _dictionaryUnit = new DictUnit<Record<string, unknown>>({ // inform DictUnit it is storing key as string and value as unknown 
    id: "registration",
    immutable: true,
    persistent: true,
    cacheSize: 200,
    // initialValue: {},
    distinctDispatchCheck: true
});

Here is the codesandbox for simple demonstration:

https://codesandbox.io/s/rough-cloud-bz51m?file=/src/app/registration-state.service.ts:255-264


P.S.

You can change the unknown type to be more restricted, like string | boolean | number.

Related