typescript - 打字稿递归类型退出条件
问题描述
据我所知,递归需要退出条件或基本条件。我DeepReadonly
在我的程序中使用这种类型。
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
type Teacher = {
name: string;
address: {
street: string;
}
};
type ReadOnlyTeacher = DeepReadonly<Teacher>; // works like a charm
type ReadOnlyString = DeepReadonly<string>; // still string
我无法理解DeepReadonly<string>
的是string
。
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
// T is type string
type DeepReadonlyString = {
readonly [P in keyof string]: DeepReadonly<string[P]>
}
我搜索了文档,但没有发现任何关于此行为的提及
解决方案
DeepReadonly<string>
是字符串,因为 readonly 只能应用于数组字面量和对象的属性。Readonly<string>
为什么是string
或为什么readonly string
是无效语法的相同原因。
'readonly' type modifier is only permitted on array and tuple literal types.
文字字符串已经是只读的。您不能修改其值。
let a = 'a';
a = 'b';
这里'a'
没有修改字符串,而是为'b'
变量分配了一个新字符串a
。
Javascript 已经允许您将变量的值设为只读,使用
const str = 'value';
推荐阅读
- azure - Azure 虚拟机 LinuxDiagnostic Extension OMI EnumerateInstances 失败(Linux 诊断 OMI)
- java - JEditorPane 内图像上的文本
- reactjs - 如何在使用 GraphQL 轮询时防止重新渲染
- sql-server - 在 SQL Server Management Studio 中使用时插入 = 问号
- javascript - 无法使用 innerHTML 和 innerText 更改标签内容
- angular - 为 Firestore 创建的每个用户的自定义 UID
- django - 否则在 django 中不起作用,我不知道如何解决这个问题
- c++ - C++ 赋值复合运算符与简单运算符结合赋值运算符
- javascript - 在 Svelte 动作上传递多个参数
- typescript - Typescript 接口属性作为通用对象的嵌套键