小编Nil*_*ier的帖子

从类型化对象派生精确类型

在 TypeScript 中,我想从这样的常量派生类型

const iso3ToCountry = {
  DEU: {
    name: "Germany",
    continent: "Europe",
    language: "de",
  },
  GBR: {
    name: "United Kingdom of Great Britain and Northern Ireland",
    continent: "Europe",
    language: "en",
  },
} as const;

type ISOCode = keyof typeof iso3ToCountry // same as "DEU" | "GBR";
Run Code Online (Sandbox Code Playgroud)

但是,我还想确保对象的值实现以下接口:

interface CountryDetails {
  name: string;
  continent: string;
  language: string;
}
Run Code Online (Sandbox Code Playgroud)

我发现实现这两个目标的唯一方法是使用辅助函数

function ensureType<T extends Record<string, CountryDetails>>(obj: T): T {
  return obj;
}

const iso3ToCountry = ensureType({
  DEU: {
    name: "Germany",
    continent: "Europe", …
Run Code Online (Sandbox Code Playgroud)

typescript

5
推荐指数
1
解决办法
3548
查看次数

标签 统计

typescript ×1