您可以使用const
type parameter来表示对类似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
.
因此,type
属性是both readonly
and a字符串literal type.
这个问题似乎没有区分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
Playground link to code个