有没有办法将所有深度嵌套对象的值类型都定义为字符串类型?

Is there a way to define all value types of deeply nested objects as all being of type string?

假设这个嵌套对象:

const nestedObj = {
  definition: {
    name: 'Mike',
    prop1: {
      value1: 'This is a string',
      prop2: {
        value2: 'String again',
      },
    },
  },
};

是否有一种谨慎的方式来做类似的事情:

type NestedObj = {
  definition: AllValuesAreOfTypeString
}

this 是您要找的东西吗?

否则,通过编写您已有的确切代码,您已经 nestedObj 了以下类型:

{
  definition: {
    name: string,
    prop1: {
      value1: string,
      prop2: {
        value2: string,
      },
    },
  },
}

例如,如果您提取嵌套属性之一:

const nestedProp = nestedObj.definition.prop1.value1;

它将正确输入为 string:

(nestedProp: string);

如果您尝试将深度嵌套的 属性 设置为不同的类型:

nestedObj.definition.prop1.value1 = 1;

您将收到类型错误:

Cannot assign 1 to nestedObj.definition.prop1.value1 because number [1] is incompatible with string [2].

您也不能在对象上设置其他道具,因为它是密封的:

nestedObj.undefinedProp = 'test';

最后,您实际上可以通过执行以下操作来保存 nestedObj 的类型:

type NestObject = typeof nestedObj;

然后,例如,您可以在其他对象上使用此类型:

const nestedObj2: NestedObject = {
  definition: {
    name: 'test',
    prop1: {
      value1: 'value1',
      prop2: {
        value2: 'test',
      }
    },
  },
};

因此,如果您以与 nestedObj1 不匹配的方式定义 nestedObj2,则会出现错误:


const nestedObj3: NestedObject = {
  definition: {
    name: 1, // Error!
    // Cannot assign object literal to `nestedObj3` because 
    // number [1] is incompatible with string [2] in property 
    // `definition.name`.
    prop1: {
      value1: 'value1',
      prop2: {
        value2: 'test',
      }
    },
  },
};

(Try Flow)

编辑:添加了第一个示例,因为我可能第一次误解了这个问题。