TS2322:类型 'boolean' 不可分配给类型 'undefined'。如何动态分配可选属性?
TS2322: Type 'boolean' is not assignable to type 'undefined'. How to assign optional properties dynamically?
我正在尝试将属性分配给一个对象以形成一个名为 ParsedArguments
的已知接口,这就是它的样子:
import {Rules} from "../Rules/types/Rules";
export interface ParsedArguments {
//other props
//...
rules?: Rules,
}
现在在另一个函数中,我试图形成一个从 cli
读取值的对象,并形成一个符合该接口的对象。像这样:
private parseCliArgs(args: string[]): ParsedArguments {
let res: ParsedArguments = {}
for (const arg of args) {
if (arg.startsWith('--')) {
const {key, value} = this.getArgValues(arg)
if (!res.rules) {
res.rules = {}
}
const rule: keyof Rules = key
if (res.rules[rule]) {
//HERE I GET THE ERROR
//TS2322: Type 'STRING' is not assignable to type 'undefined'.
res.rules[rule] = value
}
}
}
return res
}
即使我检查 Rules
的 属性 是否存在,它仍然给我这个错误。我还想不通,希望你们能帮我解决这个问题。这是 Rules
的样子:
export interface Rules {
someProp1?: boolean,
someProp2?: number,
//...
}
我也试过 const rule = key as keyof Rules
而不是 const rule: keyof Rules = key
,没有任何改变。
如果你们需要更多说明或者我遗漏了任何部分,请告诉我,我将不胜感激。提前谢谢大家。
您在 Rules
和 value
中没有兼容的类型。在 Rules
中,您有可选的 boolean
和 number
(因此它们隐含地包含 undefined
),在 value
中,您总是有 string
.
如果您将 Rules
中的所有道具都作为字符串,那么它们将是兼容的。
请参阅 this playground 以更好地理解我的意思
好的,这就是我的想法。我使用了 built-in
Typescript 泛型,这在这种情况下非常有用。因为为了获得那些动态的结果,一直定义不同的类型并不是很明智。然后你将结束类型的级联。见下文:
let rules: Partial<Record<keyof Rules, string>> = {}
for (const arg of args) {
if (arg.startsWith('--')) {
const {key, value} = this.getArgValues(arg)
if (this.isRuleKey(key)) {
rules[key] = value
}
}
}
现在有了这个解决方案,我不必创建另一个版本的 Rules
类型。一切正常。
我正在尝试将属性分配给一个对象以形成一个名为 ParsedArguments
的已知接口,这就是它的样子:
import {Rules} from "../Rules/types/Rules";
export interface ParsedArguments {
//other props
//...
rules?: Rules,
}
现在在另一个函数中,我试图形成一个从 cli
读取值的对象,并形成一个符合该接口的对象。像这样:
private parseCliArgs(args: string[]): ParsedArguments {
let res: ParsedArguments = {}
for (const arg of args) {
if (arg.startsWith('--')) {
const {key, value} = this.getArgValues(arg)
if (!res.rules) {
res.rules = {}
}
const rule: keyof Rules = key
if (res.rules[rule]) {
//HERE I GET THE ERROR
//TS2322: Type 'STRING' is not assignable to type 'undefined'.
res.rules[rule] = value
}
}
}
return res
}
即使我检查 Rules
的 属性 是否存在,它仍然给我这个错误。我还想不通,希望你们能帮我解决这个问题。这是 Rules
的样子:
export interface Rules {
someProp1?: boolean,
someProp2?: number,
//...
}
我也试过 const rule = key as keyof Rules
而不是 const rule: keyof Rules = key
,没有任何改变。
如果你们需要更多说明或者我遗漏了任何部分,请告诉我,我将不胜感激。提前谢谢大家。
您在 Rules
和 value
中没有兼容的类型。在 Rules
中,您有可选的 boolean
和 number
(因此它们隐含地包含 undefined
),在 value
中,您总是有 string
.
如果您将 Rules
中的所有道具都作为字符串,那么它们将是兼容的。
请参阅 this playground 以更好地理解我的意思
好的,这就是我的想法。我使用了 built-in
Typescript 泛型,这在这种情况下非常有用。因为为了获得那些动态的结果,一直定义不同的类型并不是很明智。然后你将结束类型的级联。见下文:
let rules: Partial<Record<keyof Rules, string>> = {}
for (const arg of args) {
if (arg.startsWith('--')) {
const {key, value} = this.getArgValues(arg)
if (this.isRuleKey(key)) {
rules[key] = value
}
}
}
现在有了这个解决方案,我不必创建另一个版本的 Rules
类型。一切正常。