打字稿为方法参数定义类型

Typescript define type for method argument

我有一个公司对象,看起来像这样:

{ 
 tracking_hours: {
  open: '8:00',
  close: '20:00'
 }
}

我用它来设置值:

set({
 openTime: setTime(company, 'open_time'),
 closeTime: setTime(company, 'close_time'),
})

我需要以某种方式在 setTime 函数中为公司设置类型

export function setTime(
    company: {
        tracking_hours: null | any
    },
    type: string,
): number | null {
    if (company.tracking_hours) {
        if (company.tracking_hours[type]) {
            const time = Number(company.tracking_hours[type].split(':')[0])

            if (time) {
                return time
            } else {
                return null
            }
        }

        return null
    }

    return null
}

如何用实际类型替换 any

这可以通过

来完成
  • Company
  • 创建一个单独的类型
  • 使用 keyof 指示 type
  • 的正确类型
const company = {
  tracking_hours: {
    open: "8:00",
    close: "20:00",
  },
};

interface Company {
  tracking_hours: {
    open: string;
    close: string;
  };
}

function setTime(
  company: Company,
  type: keyof Company["tracking_hours"]
): number | null {
  const time = Number(company.tracking_hours[type].split(":")[0]);

  return time ?? null
}

setTime(company, "open");
setTime(company, "close");

请注意,我已经简化了您的一些代码,因为

  • 您不需要检查 company.tracking_hourscompany.tracking_hours[type] 是否存在 - TypeScript 保证它们将始终存在,因为函数签名中指定了类型
  • 您只需要 return null 一次,因为所有其他情况都会从相应的块中退出并命中最终的 return 语句。