用于将对象数组转换为带有数组对象中的键的对象的打字稿类型

问题描述 投票:0回答:1

interface Item {
  slug: string;
  description: string;
}

interface Params {
  id: number;
  items: Item[];
}

function test(params: Params) {
  const result = {};
  
  for (const item of params.items) {
    result[item.slug] = "Hello";
  }
  
  return result;
}


const data = {
  id: 3,
  items: [
    { slug: "one", description: "This is one" },
    { slug: "two", description: "This is two" },
    { slug: "three", description: "This is three" },
  ]
}

const final = test(data)

好的。我有数据并将其传递给测试函数。测试函数返回一个对象,其中的键作为项目中 slugs 的值和一个字符串值。所以我希望final变量的类型是这样的:

{
  one: string;
  two: string;
  three: string;
}

不是这个:

Record<string, string>

我的意思是它必须从项目中提取 slug 值并用它创建一个对象。明确告知类型。如何定义测试函数的返回类型来实现此目的? 谢谢。

javascript arrays typescript object
1个回答
0
投票

如果您的数据是“静态”的,您可以使用

as const
将其标记为常量,现在您的 slug 类型不是字符串,而是字符串文字:


interface Item {
  slug: string;
  description: string;
}

interface Params {
  id: number;
  items: Item[];
}

const data = {
  id: 3,
  items: [
    { slug: "one", description: "This is one" },
    { slug: "two", description: "This is two" },
    { slug: "three", description: "This is three" },
  ]
} as const

type Data = typeof data

type Slug = Data["items"][number]["slug"]

type Mapping = Record<Slug,string>

或者这里是游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.