如何让泛型更加具体?

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

有一个功能

function createStats<K extends string[]>(arr: K): Stats<K[number]>

当我这样做时

const testStats = createStats(["maxHealth"])

testStats 是

Stats<string>
,我希望它是
Stats<"maxHealth">

我知道如何修复它的唯一方法是添加

as const
。但我不想在我的所有代码中都写
as const
,所以这对我来说并不是一个好的解决方案。

typescript generics
1个回答
1
投票

您可以使用通用

const
类型参数,也称为
const
修饰符。与
const
-断言
类似,它将尝试推断通用参数的最具体类型。

declare function createStats<const K extends readonly string[]>(
  arr: K,
): Stats<K[number]>;
createStats(["maxHealth"]);
//^? function createStats<["maxHealth"]>(arr: ["maxHealth"]): "maxHealth"

TypeScript 游乐场

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