![](/img/trans.png)
[英]error TS2345: Argument of type 'Menu' is not assignable to parameter of type
[英]TS2345: Argument of type 'string' is not assignable to parameter of type 'never'
我有以下 Angular 服务
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
}
}
我将服务注入到我的组件中:
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 })
}
}
集合 function 的 API 位于https://api.activejs.dev/classes/dictunit.html#set
为什么我会得到这个结果?
我正在使用以下 #1 "typescript": "~4.1.5" - strict mode #2 "@angular/cli": "^11.2.12", #3 Linux Mint Ulyana
谢谢
需要明确地通知DictUnit
它正在存储什么数据类型。 如果没有指定,它将使用Record<never, never>
。
因此,在您的组件 class 中设置年龄时,它会警告您类型不兼容(字符串。= 从不)。
一个简单的修复将是这样的:
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
});
这是用于简单演示的代码框:
https://codesandbox.io/s/rough-cloud-bz51m?file=/src/app/registration-state.service.ts:255-264
附言
您可以将未知类型更改为更受限制,例如string | boolean | number
string | boolean | number
string | boolean | number
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.