javascript 获取错误“参数类型”字符串|“undefined”不能分配给类型”的参数

ycl3bljg  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(243)

我得到下面的错误**“参数类型'字符串|undefined' is not assignable to parameter of type”**我不知道如何解决这个错误..这是我的代码

export interface IDropDown {
  label: string;
  value: string;
}
export enum BOOKING_TYPE {
  FC = 'FC',
  LC = 'LC',
  TUFFING = 'TUFFING',
}
  export interface IImportBookingData {
      booking_type: IDropDown | null;
  }
  let bookingData: IImportBookingData;
  const iscl = [BOOKING_TYPE.LC, BOOKING_TYPE.TUFFING].indexOf(bookingData?.booking_type?.value) !== -1;

  console.log(iscl)

字符串
码链接
https://www.typescriptlang.org/play?ssl=17&ssc=1&pln=1&pc=1#code/ATCmA8AcHsCcBdgEsB29SwGYEMDGpgBJAEVmkmOgHcVgBvAWACgQAbbAI1FYC5gBneLFQBzANzMQAN2ysArqD6DhKccwC+zCDARgUcgLbAAQgHlTAaUIA5AOIB9ACoBNAAoBRepOAAxAMLAALzAAOT+IQA03gAyAcEhsZHejgCqPj42tkGhqemZSUyaLGBQcIio6Fh4BISEBjrwxtDQANaixNjw2F7FICAczW2q9vAAnpCKRKTklDTAAD7A+qysEsVFbKCIA63tndh8tfVlTbuqHV1rILjQKILI-Lis2QDaZpaZTm7uAHSxESZzFY7F8PD9chk7ABdH6oAAmEFMmAAFDshiILtgAPw-NGiEbjUA4mTyUAASmAAEJAsEALQARjW3hud2grFAP1Y0BEyKQj1YZOYQA
知道吗?


的数据

g52tjvyc

g52tjvyc1#

类型booking_type被定义为IDropDown。但是,稍后您将访问indexOfbooking_typevalue属性。
在这里,valuestring,它将显示类型错误。为了克服这个问题,你需要类型转换值。

const iscl = [BOOKING_TYPE.LC, BOOKING_TYPE.TUFFING]
   .indexOf((bookingData?.booking_type?.value) as BOOKING_TYPE) !== -1;

字符串
在这里,as BOOKING_TYPE将处理类型转换错误。

sqserrrh

sqserrrh2#

export enum BOOKING_TYPE {
  FC = 'enumFC',
  LC = 'LC',
  TUFFING = 'TUFFING',
}
export interface IDropDown {
  label: string;
  value: BOOKING_TYPE; // value should be of type BOOKING_TYPE
}
export interface IImportBookingData {
    booking_type: IDropDown;
}
// assing value first
let bookingData: IImportBookingData = {
  booking_type: 
  {label:"hello", value: 'LC'}
};

const iscl = [BOOKING_TYPE.LC, BOOKING_TYPE.TUFFING]
                     .indexOf(bookingData.booking_type.value) !== -1;

console.log(iscl)

字符串

同时检查此解决方案

// export enum BOOKING_TYPE {
//   FC = 'enumFC',
//   LC = 'LC',
//   TUFFING = 'TUFFING',
// }

export type BOOKING_TYPE = "enumFC" | "LC" | "TUFFING";

export interface IDropDown {
  label: string;
  value: BOOKING_TYPE;
}
export interface IImportBookingData {
    booking_type: IDropDown;
}
// assing value first
let bookingData: IImportBookingData = {
  booking_type: 
  {label:"hello", value: 'LC'}
};

// const iscl = [BOOKING_TYPE.LC, BOOKING_TYPE.TUFFING]
//                     .indexOf(bookingData.booking_type.value) !== -1;
const iscl = ["LC", "TUFFING"].indexOf(bookingData.booking_type.value) !== -1;

console.log(iscl)


希望这能解决你的问题。

相关问题