作为const`替代缩小数组字面元组的替代方案,以避免``readonly''修饰符

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

我们使用

as const
缩小类型:

[ {foo: 'foo' }, { bar: 'bar' } ] as const

但这还为所有道具和值添加了

readonly
修饰符。在
const
中,这使得我想缩小狭窄,而没有修改器,因为您想修改元组中的对象,或者只是将其进一步传递给某种方法,这是相同的方法界面,但没有深度
readonly
readonly

在这里,foo是类型的:

let foo = [ {foo: 'foo' }, { bar: 'bar' } ]

,但我希望能得到
({ foo: string; bar?: undefined; } | { bar: string; foo?: undefined; })[]

我们使用
[{
    foo: string;
}, {
    bar: string;
}]
,但是在大多数情况下,由于

as const

/
foo
获得深度嵌套的修饰符,因此我们可以使用类似
bar
但是它将使用添加
readonly

type DeepWritable<T> = { -readonly [P in keyof T]: DeepWritable<T[P]> };
,然后将其删除。

您是否知道任何替代方案

as const
在不手动定义类型的情况下缩小元组类型的范围。
	
您可以使用以下通用函数将类型限制为元组:
readonly

然后包裹文字:

DeepWritable

typescript typescript-typings
2个回答
7
投票

here是一个更好的通用功能,因为它也保留了元组成员字面价值:

as const

这样吗:

const Tuple = <T extends [any, ...any]>(v:T) => v

0
投票
Relevanttyscript 3.4发行注释for Reference。 还值得检查这个相关的,更彻底的答案

    

发现更好的方法:

let foo = Tuple([ {foo: 'foo' }, { bar: 'bar' } ]) // foo: [{ foo: string }, { bar: string }]

值得注意的是您必须使用
Tuple
而不是

export type Writable<T> = { -readonly [K in keyof T]: T[K]; }; export const Tuple = <T extends readonly [unknown, ...unknown[]]>(v: T) => v as Writable<T>;

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.