[英]typescript conditional type on generic
I have a type in a shape like this (simplified):我有一个像这样形状的类型(简化):
type AllContentType =
| 'application/json'
| 'application/octet-stream'
| 'multipart/form-data';
type myType<T = AllContentType> = {
body: T extends 'multipart/form-data' ? number : string;
otherHeader: T;
};
and it cannot figure out which string has been put into otherHeader
, it always returns并且它无法确定将哪个字符串放入otherHeader
,它总是返回
const obj: myType = { header: 'multipart/form-data', body: "" };
body
as string | number
body
作为string | number
string | number
. string | number
。 Any way to get it to figure out what I actually have put in?有什么方法可以让它弄清楚我实际输入了什么?
By giving your type parameter a default value通过给你的类型参数一个默认值
type myType<T = AllContentType>
writing this写这个
const obj: myType = { otherHeader: 'multipart/form-data', body: "" };
is effectively是有效的
const obj: myType<AllContentType> = { otherHeader: 'multipart/form-data', body: "" };
which makes the predicate T extends 'multipart/form-data'
false.这使得谓词T extends 'multipart/form-data'
假。
If you leave out the default value for the type parameter and specify the type explicitly, it would work properly:如果省略 type 参数的默认值并明确指定类型,它将正常工作:
type myType<T extends AllContentType> = {
body: T extends 'multipart/form-data' ? number : string;
otherHeader: T;
};
const obj: myType<'multipart/form-data'> = { otherHeader: 'multipart/form-data', body: "" };
although that adds repetition.虽然这增加了重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.