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 - Fatal编程技术网

Typescript 通过泛型缩小类型脚本索引类型

Typescript 通过泛型缩小类型脚本索引类型,typescript,Typescript,考虑以下类型: 类型请求规范={ 键入:“get”|“post”; 参数:{[key:string]:ParameterSpecification} }; 类型参数规格={ 必需:布尔值; // ... } 现在需要创建如下变量: const requestSpecification:requestSpecification={ 键入:“获取”, 参数:{ 身份证:{ 必填项:true }, 昵称:{ 必填项:false } } } 我们不能调用requestSpecification.pa

考虑以下类型:

类型请求规范={
键入:“get”|“post”;
参数:{[key:string]:ParameterSpecification}
};
类型参数规格={
必需:布尔值;
// ...
}
现在需要创建如下变量:

const requestSpecification:requestSpecification={
键入:“获取”,
参数:{
身份证:{
必填项:true
},
昵称:{
必填项:false
}
}
}
我们不能调用
requestSpecification.parameters的现有属性:

// no error!!!
console.log(requestSpecification.parameters.asdf);
我希望TypeScript知道在
参数中只有
id
昵称
可用。
如何通过泛型解决它?

您正在使用的字符串索引类型告诉TypeScript,
参数可以具有任何字符串属性。换句话说,
'asdf'
(以及任何其他字符串)都可以作为属性。不允许将数字作为属性。因为这是您声明的类型,所以TypeScript的行为与预期的一样,因为它允许
'asdf'
作为
参数的属性

这是关于字符串索引类型的常见混淆,在您的TypeScript职业生涯中,它可能会一次又一次地让您大吃一惊

缩小类型范围的一种方法是。在下面的示例中,我们说
P
扩展字符串。因此,
参数
仍受字符串属性的约束。当我们实例化该类型时,我们传递的是一个字符串联合
'id'|'nickname'
。这会准确地告诉编译器允许使用哪两个字符串

type RequestSpecification<P extends string> = {
  type: "get" | "post";
  parameters: { [K in P]: ParameterSpecification }
};

type ParameterSpecification = {
  required: boolean;
}

const requestSpecification: RequestSpecification<'id' | 'nickname'> = {
    type: "get",
    parameters: {
        id: {
            required: true
        },
        nickname: {
            required: false
        }
    }
}

// This will now be a compiler error. Hooray! 
console.log(requestSpecification.parameters.asdf);
类型请求规范={
键入:“get”|“post”;
参数:{[K in P]:参数规范}
};
类型参数规格={
必需:布尔值;
}
常量请求规范:请求规范={
键入:“获取”,
参数:{
身份证:{
必填项:true
},
昵称:{
必填项:false
}
}
}
//这将是一个编译器错误。好极了
log(requestSpecification.parameters.asdf);

你的tsconfig.json中有
严格的
标志吗?@Evert,是的,我有。