Typescript 类型防护装置,将一般类型T缩小为拾取<;T、 U>;
我有一个类型保护,其唯一目的是检查对象中是否存在属性,以及它是否具有某些价值 对于类型系统,我想对编译器说这个短语,如果类型保护检查成功: 这是一个输入对象,如果类型保护成功,那么输出就是一个对象 具有线宽属性 对于精确的对象,它如下所示:Typescript 类型防护装置,将一般类型T缩小为拾取<;T、 U>;,typescript,typescript-generics,Typescript,Typescript Generics,我有一个类型保护,其唯一目的是检查对象中是否存在属性,以及它是否具有某些价值 对于类型系统,我想对编译器说这个短语,如果类型保护检查成功: 这是一个输入对象,如果类型保护成功,那么输出就是一个对象 具有线宽属性 对于精确的对象,它如下所示: 类型PickedLineHeight=拾取 类型NonNullableLineHeight=必需 函数hasLineHeight(样式:对象):样式为非NullLineHeight{ 返回( style.hasOwnProperty(“线宽”)&& (样式为
类型PickedLineHeight=拾取
类型NonNullableLineHeight=必需
函数hasLineHeight(样式:对象):样式为非NullLineHeight{
返回(
style.hasOwnProperty(“线宽”)&&
(样式为PickedLineHeight)。线宽!==未定义
)
}
如何开发更通用的函数版本,如hasProperty(style,prop)
我的尝试是:
函数hasProperty(style:T,prop:U):样式为Pick{
返回(
style.hasOwnProperty(道具)&&
样式[道具]!==未定义
)
}
但我经常收到这个错误信息,我无法消除或理解
我偶然想到了这个解决方案,我认为,这个解决方案和显示错误的解决方案是一样的 但不管怎么说,这是毫无怨言的:
函数hasProperty(style:T,prop:keyof T):样式为Pick{
返回(
style.hasOwnProperty(道具)&&
样式[道具]!==未定义
)
}
函数hasFontSize(样式:TextStyle){
返回属性(样式“fontSize”)
}
函数hasLineHeight(样式:TextStyle){
返回属性(样式“线宽”)
}
我可能会这样键入hasProperty()
:
function hasProperty<T extends object, K extends keyof T>(
style: T,
prop: K
): style is T & { [P in K]-?: Exclude<T[K], undefined> } {
return style.hasOwnProperty(prop) && style[prop] !== undefined;
}
看起来不错。好的,希望能有帮助。祝你好运
非常感谢!这正是我想要的。这些类型表示对象上存在属性。但Typescript仍然假定该属性下的值可以是
未定义的。
interface Example {
required: string;
optional?: string;
requiredButPossiblyUndefined: string | undefined;
requiredButPossiblyNull: string | null;
}
function checkExample(ex: Example) {
ex.required.toUpperCase(); // okay
// hasProperty de-optionalizes optional properties
ex.optional.toUpperCase(); // error, possibly undefined
if (hasProperty(ex, "optional")) {
ex.optional.toUpperCase(); // okay
}
// hasProperty removes undefined from list of possible values
ex.requiredButPossiblyUndefined.toUpperCase(); // error, possibly undefined
if (hasProperty(ex, "requiredButPossiblyUndefined")) {
ex.requiredButPossiblyUndefined.toUpperCase(); // okay
}
// hasProperty doesn't do anything with null
ex.requiredButPossiblyNull.toUpperCase(); // error, possibly null
if (hasProperty(ex, "requiredButPossiblyNull")) {
ex.requiredButPossiblyNull.toUpperCase(); // error, possibly null
}
}