Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端 select options 如何定义 TS 数据类型? #319

Open
xxleyi opened this issue Aug 18, 2021 · 0 comments
Open

前端 select options 如何定义 TS 数据类型? #319

xxleyi opened this issue Aug 18, 2021 · 0 comments
Labels

Comments

@xxleyi
Copy link
Owner

xxleyi commented Aug 18, 2021

前端下拉筛选通常是一个 value 和 code 的对应关系数组,但基于这个数据,也会有其他映射需求,比如从 code 映射到 value,或从 value 映射到 code,甚至 value 和 code 自身的类型也想确定。此时需要考虑的点就比较多,但我们可以抓住一点:信息的来源只有一点,其他只是形式的变换:

// single truth
const industryOptions = [
  {
    name: '电器',
    code: 1,
  },
  {
    name: '生鲜',
    code: 2,
  },
  {
    name: '游戏',
    code: 3,
  },
] as const;


// derivate from top
type IndustryOptions = typeof industryOptions
type IndustryOptionsIndexUnion = keyof IndustryOptions & `${number}`
type NameMapCode = {[index in IndustryOptionsIndexUnion as IndustryOptions[index]['name']]: IndustryOptions[index]['code']}
type CodeMapName = {[index in IndustryOptionsIndexUnion as IndustryOptions[index]['code']]: IndustryOptions[index]['name']}
type IndustryCode = keyof CodeMapName
type IndustryName = keyof NameMapCode

const nameMapCode = industryOptions.reduce((acc, cur) => ({...acc, [cur.name]: cur.code}), {}) as NameMapCode
const codeMapName = industryOptions.reduce((acc, cur) => ({...acc, [cur.code]: cur.name}), {}) as CodeMapName
@xxleyi xxleyi added the HOW label Aug 18, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant