You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义符合文件后缀类型约束的TypeScript Files类型?

问题

规则要求:文件名以.png、.jpg、.gif结尾时,对应值必须为Uint8Array类型,否则为string类型。现有示例代码如下:

const files: Files = {
  "assets/logo.png": new Uint8Array(2),
  "overview.txt": "This is a txt file",
  "src/index.js": "console.log('index')"
}

type Files = ?

我尝试了以下写法,但不确定是否正确:

enum BinaryFile {
    PNG = ".png",
    JPG = ".jpg",
    GIF = ".gif"
}

type Files = {
    [P in string]: P extends `${string}${BinaryFile}` ? Uint8Array: string
}
解答

你的思路是对的,但有个小问题:TypeScript 里枚举在模板字符串类型里的处理得确保枚举成员是字面量类型,而且直接用[P in string]会让类型太宽泛,没法精准约束对象的键值对应关系。

正确的定义可以直接用模板字符串联合类型实现,不用枚举:

type BinaryExt = '.png' | '.jpg' | '.gif';
type Files = {
  [K: string]: K extends `${string}${BinaryExt}` ? Uint8Array : string;
};

要是想保留枚举写法,得把枚举改成const enum,保证成员是字面量类型:

const enum BinaryFile {
    PNG = ".png",
    JPG = ".jpg",
    GIF = ".gif"
}

type Files = {
    [K: string]: K extends `${string}${BinaryFile}` ? Uint8Array : string;
};

这两种写法都能满足需求:对象键以指定后缀结尾时,值必须是Uint8Array,其他情况则为string。

内容的提问来源于stack exchange,提问作者Cihad Paksoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:14:53