首页 > 解决方案 > 打字稿递归类型退出条件

问题描述

据我所知,递归需要退出条件或基本条件。我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]>
}

我搜索了文档,但没有发现任何关于此行为的提及

标签: typescripttypescript-generics

解决方案


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';

推荐阅读