Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 递归对象生成_Typescript_Recursive Type - Fatal编程技术网

Typescript 递归对象生成

Typescript 递归对象生成,typescript,recursive-type,Typescript,Recursive Type,我需要对任何对象结构进行类型检查,该对象结构具有以前未知的数字属性 type Test={[key:string]:Test}编号; //类型Test={[key:string]:Test | number};//同样的问题 //这是一个对象结构的示例。我事先不知道它的真实结构。 let test:test={a:{b:{c:2},d:2,faild:'cause string'};//类型检查工作正常 //类型检查不适用于以下所有示例-BUG? //test.obj=>any //类型“Tes

我需要对任何对象结构进行类型检查,该对象结构具有以前未知的数字属性

type Test={[key:string]:Test}编号;
//类型Test={[key:string]:Test | number};//同样的问题
//这是一个对象结构的示例。我事先不知道它的真实结构。
let test:test={a:{b:{c:2},d:2,faild:'cause string'};//类型检查工作正常
//类型检查不适用于以下所有示例-BUG?
//test.obj=>any
//类型“Test”上不存在属性“obj”。
//类型“number”上不存在属性“obj”。(2339)
测试对象x.y.z;
试验对象x.y.z=2;
test.obj.x.y.faild='因为字符串';
test.obj;
test.obj=2;
test.obj.faild='因为字符串';

该错误与这样一个事实有关,即此类类型从未定义给定属性是否具有对象或数字值,因此TS在第一级投诉您无法访问属性,因为它可能只是一个数字,而数字类型没有属性。这在错误中完全可见:

类型“number”上不存在属性“obj”

在该对象的每个级别,TS只知道它是带有字符串键的
对象| number
,这不足以允许访问下一个属性,因为在运行时,我们可以处理
number
,并有运行时异常。这正是我们想要通过使用TS来防止的,不是吗

为了告诉TS在给定的字段中有一个对象,我们需要使用泛型和简单的id函数来更好地缩小类型

type Test = {[key: string]: Test} | number;
// function which just pass object through but allows for exact type inferring
function makeObj<T extends Test>(arg: T): T {
    return arg;
}

let test = makeObj({a: {b: {c:2}, d: 2, faild: 'because string'}}); // error expected

let test2 = makeObj({a: {b: {c:2}, d: 2, works: 2}}); // success

test2.a.works = 2;
test2.a.b.c = 2;
test2.a.b.c;
test2.a.works = 'string'; // error as expected
type Test={[key:string]:Test}编号;
//只传递对象,但允许精确类型推断的函数
函数makeObj(参数:T):T{
返回arg;
}
让test=makeObj({a:{b:{c:2},d:2,faild:'cause string'}});//预期错误
设test2=makeObj({a:{b:{c:2},d:2,works:2});//成功
test2.a.works=2;
测试2.a.b.c=2;
测试2.a.b.c;
test2.a.works='string';//错误如预期

在上面的示例中,TS完全是在推断类型,因为它知道给定属性中可以有什么值。链接到

一个小便笺-您可能想将
|编号
移动到字体内部?或者你说
Test
可以是一个对象的数字,即使是在外层?另外,请务必在帖子中包含相关信息,但不要作为代码截图,谢谢!