使用const storage : Readonly<{id: string}[]>,如何在storage中的静态id中键入一些string?该数组在运行时不会更改,并且被硬编码在中.

我试过(typeof storage)[number]['id'],但只有string.也试过satisfies Readonly<{id:string}[]>

interface HasID {
  id: string
  info?: any
}
const storage : Readonly<HasID[]> = [
 { id: 'foo' },
 { id: 'bar', info: ['baz'] }
]
const storage2 = [
  { id: 'foo' },
  { id: 'bar', info: ['baz'] }
] satisfies Readonly<HasID[]>

let str // looking to type this to be "foo" | "bar"

type StorageID = (typeof storage)[number]['id'] // string
type StorageID2 = (typeof storage2)[number]['id'] // string

推荐答案

通常,当人们写array literalsobject literals时,他们只是试图初始化一些可变变量,并期望内容发生变化.所以TypeScript对这些进行了相当广泛的推断. 所以即使是the satisfies operator,你也会得到比你想要的更宽的东西:

const storage = [
  { id: 'foo' },
  { id: 'bar', info: ['baz'] }
] satisfies Readonly<HasID[]>;
/*
const storage: ({
    id: string;
    info?: undefined;
} | {
    id: string;
    info: string[];
})[]
*/

id处房产中的特定literal types处已经丢失.


在不打算更改文本对象或数组的内容的情况下,you can use 100让TypeScrip推断出更具体的类型:

const storage = [
  { id: 'foo' },
  { id: 'bar', info: ['baz'] }
] as const satisfies Readonly<HasID[]>
/* 
const storage: readonly [{
    readonly id: "foo";
}, {
    readonly id: "bar";
    readonly info: readonly ["baz"];
}]
*/

该类型跟踪id属性的文字类型(以及数组元素的顺序). 现在你使用indexed access types的方法将按预期工作:

type StorageID = (typeof storage)[number]['id']
//   ^? type StorageID = "foo" | "bar"

Playground link to code

Typescript相关问答推荐

使用FormArray在Angular中添加排序

Angular 过滤器形式基于某些条件的数组控制

角形标题大小写所有单词除外

typescribe警告,explate—deps,useEffect依赖项列表

为什么tsx不判断名称中有"—"的属性?'

Express Yup显示所有字段的所有错误

如何实现异构数组内函数的类型缩小

如果数组使用Reaction-Hook-Form更改,则重新呈现表单

FatalError:Error TS6046:';--模块分辨率';选项的参数必须是:'; node ';,'; node 16';,'; node

如何以Angular 导入其他组件S配置文件

try 呈现应用程序获取-错误:动作必须是普通对象.使用自定义中间件进行MySQL操作

在React中定义props 的不同方式.FunctionalComponent

RXJS将对键盘/鼠标点击组合做出react

在TypeScript中扩展重载方法时出现问题

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

有没有一种方法可以防止我的组件包在其中安装样式组件'; node 模块中的s目录

如何实现允许扩展泛型函数参数的类型

如何向我的自定义样式组件声明 custom.d.ts ?

如何通过nx找到所有受影响的项目?

解析错误:DeprecationError: 'originalKeywordKind' 自 v5.0.0 起已被弃用,无法再使用