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 值并用它创建一个对象。明确告知类型。如何定义测试函数的返回类型来实现此目的? 谢谢。
如果您的数据是“静态”的,您可以使用
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>