我想使用数组函数includes
。但是内部参数“ searchElement”的类型为never
。这对我来说毫无意义,因为我可以进行单个==
比较,并且代码完成且没有类型-错误:
export default async function getValidationObjectForEnergyType(energyType: keyof IdentificatorToEnergytypeMapping): Promise<void> {
const energyTypeIdentificators: IdentificatorToEnergytypeMapping = {
Strom: [
"contactInformationLabel",
"contractNumberLabel",
"emailLabel",
"phoneLabelPower",
"zipLabelPower"
],
Gas: [
"contactInformationLabelGas",
"contractNumberLabelGas",
"emailLabelGas",
"phoneLabelGas",
"zipLabelGas"
],
};
// this is okay
energyTypeIdentificators[energyType][0] == "emailLabel";
// but this is not ?!
energyTypeIdentificators[energyType].includes("emailLabel")
}
// Types:
interface IdentificatorToEnergytypeMapping {
Strom: MrInputKeysPower[];
Gas: MrInputKeysGas[];
}
type MrInputKeysPower = keyof MrInputsPower;
type MrInputKeysGas = keyof MrInputsGas;
interface MrInputsPower {
contactInformationLabel: string;
contractNumberLabel: string;
emailLabel: string;
phoneLabelPower: string;
zipLabelPower: string;
}
interface MrInputsGas {
contactInformationLabelGas: string;
contractNumberLabelGas: string;
emailLabelGas: string;
phoneLabelGas: string;
zipLabelGas: string;
}
打字稿给我以下错误:
Argument of type '"emailLabel"' is not assignable to parameter of type 'never'
也许我误会了,但感觉像是打字稿-错误。
当我使用energyType: string
作为参数时,部分energyTypeIdentificators[energyType].includes("emailLabel")
的行为与预期的一样。
答案 0 :(得分:0)
检查代码后,我想我知道为什么会这样。本质上,const energyTypeIdentificators: IdentificatorToEnergytypeMapping
具有两个数组作为属性。两者的类型也是接口数组(分别为MrInputKeysPower
和MrInputKeysGas
),它们不是字符串。因此,当您传递string
以使用includes
进行搜索时,总是'never'
,因为这是因为您试图将string
与特定接口({{ 1}}或MrInputKeysPower
),这绝对不是MrInputKeysGas
。比较string
仅在接口中任何属性的名称为true时执行,如果不是名称,则会发生此错误:
==
由于此,您应该以这种方式检查电子邮件:
This condition will always return 'false' since the types '"contactInformationLabel" | "contractNumberLabel" | "emailLabel" | "phoneLabelPower" | "zipLabelPower" | "contactInformationLabelGas" | "contractNumberLabelGas" | "emailLabelGas" | "phoneLabelGas" | "zipLabelGas"' and '"foo"' have no overlap.
或
if(energyTypeIdentificators[energyType]["emailLabel"]){
}
即使您可以使用if(energyTypeIdentificators[energyType].emailLabel){
}
进行检查:
undefined