TS經過Key得到對象的value值的四種辦法

js 的情景

數據對象

export const routesMap = {
    templates: {
        name: "commonTitle_nest",
        icon: "thunderbolt",
        path: "/pageCenter/nestRoute",
        exact: true,
        redirect: "/pageCenter/light",
        key: uuid()
    },

    login: {
        name: "commonTitle_login",
        path: "/pageCenter/login",
        exact: true,
        component: lazyImport(() =>
            import('./login/index')
        ),
        key: uuid()
    },

    moderate: {
        path: "/pageCenter/moderate",
        name: "Moderate of React",
        icon: "fire",
        isNoFormat:true,
        redirect: "/pageCenter/start",
        key: uuid()
    },
}
複製代碼

取值的邏輯

if (typeof pathKey === "object") {
  let queryData = Object.entries(pathKey)[0];
  route = Object.values(routesMap).find((item) => {
    let pKey = queryData[0];
    return item[pKey] == queryData[1];
  });
}
複製代碼

第一種:修改 Tsconfig

{
  "compilerOptions": {
    ...
    "suppressImplicitAnyIndexErrors": true
    ...
  },
  ...
}

複製代碼

不推薦markdown

第二種:使用 any

取值的邏輯

if (typeof pathKey === "object") {
  let queryData = Object.entries(pathKey)[0];
  route = Object.values(routesMap).find((item: any) => {
    let pKey = queryData[0];
    return item[pKey] == queryData[1];
  });
}
複製代碼

不推薦,至關於沒用 ts架構

第三種:藉助 keyof

取值的邏輯

if (typeof pathKey === "object") {
  let queryData = Object.entries(pathKey)[0];
  route = Object.values(routesMap).find((item) => {
    let pKey = queryData[0];
    return item[pKey as keyof typeof item] == queryData[1];
  });
}
複製代碼

尚可ui

第四種:優雅

約束數據對象

type routesMapItemType = {
  name: string,
  icon?: string,
  path: string,
  exact?: boolean,
  redirect?: string,
  key: string,
  component?: any,
  isNoFormat?: boolean,
};

//不用每條屬性都寫,這麼寫能夠更好的擴展,路架構強調的
type routesMapType = { [key: string]: routesMapItemType };

export const routesMap: routesMapType = {
  templates: {
    name: "commonTitle_nest",
    icon: "thunderbolt",
    path: "/pageCenter/nestRoute",
    exact: true,
    redirect: "/pageCenter/light",
    key: uuid(),
  },

  login: {
    name: "commonTitle_login",
    path: "/pageCenter/login",
    exact: true,
    component: lazyImport(() => import("./login/index")),
    key: uuid(),
  },

  moderate: {
    path: "/pageCenter/moderate",
    name: "Moderate of React",
    icon: "fire",
    isNoFormat: true,
    redirect: "/pageCenter/start",
    key: uuid(),
  },
};
複製代碼

取值的邏輯

文件中引入類型

type routesMapItemType = {
  name: string;
  icon?: string;
  path: string;
  exact?: boolean;
  redirect?: string;
  key: string;
  component?: any;
  isNoFormat?: boolean;
};
複製代碼
if (typeof pathKey === "object") {
  let queryData = Object.entries(pathKey)[0] as (keyof routesMapItemType)[];
  route = Object.values(routesMap).find((item) => {
    let pKey = queryData[0];
    return item[pKey] == queryData[1];
  });
}
複製代碼

qanglee推薦,很是悠亞。spa

相關文章
相關標籤/搜索