提问人:Hello Hello 提问时间:9/25/2023 更新时间:9/25/2023 访问量:41
显式推断对象为只读
Explicitly infer object as readonly
问:
我有一个函数可以接收一个对象
declare function f<T extends object>(body: T): any;
f({
type: "object",
})
函数签名如下所示:
function f<{
type: string;
}>(body: {
type: string;
}): any
但我希望它是:
function f<{
type: "object";
}>(body: {
type: "object";
}): any
在传递对象时没有实际使用 as const。
有什么方法可以将对象类型显式推断为只读?
答:
1赞
jcalz
9/25/2023
#1
您可以使用 const
类型参数来指示对类似 const-assertion
的推理的偏好:
declare function f<const T extends object>(body: T): any;
f({ type: "object" })
/* function f<{ readonly type: "object"; }>(
body: { readonly type: "object"; }
): any */
这里,对象文本的类型被推断为 ,不需要显式 .{ type: "object" }
{ readonly type: "object" }
as const
所问的问题似乎没有区分和字面属性,所以我想这里并不重要。但请注意,一般来说,属性不需要是文本类型,文本类型属性也不需要是:readonly
readonly
readonly
const readonlyNotLiteral: { readonly a: string } = { a: "abc" };
readonlyNotLiteral.a = "def"; // error
readonlyNotLiteral.a = "abc"; // error
const literalNotReadonly: { a: "abc" } = { a: "abc" };
literalNotReadonly.a = "def"; // error
literalNotReadonly.a = "abc"; // okay
评论