【发布时间】:2019-02-10 18:59:42
【问题描述】:
我无法正确实现泛型 isEmpty(value),将提供的值的类型限制缩小到它的空对应项。
用例:
function getCountryNameById(countries: LookupItem[] = [], countryId?: number): string | undefined {
if (isEmpty(countries) || !isNumber(countryId)) {
// within this branch I would like to get countries argument to be narrowed to empty array type.
// Same would apply for other function which can have argument type of object or string. Why ? -> to prevent someone to do some mad code hacks like accessing non existent value from empty array ( which would happen on runtime ofc ) on compile time
// $ExpectType []
console.log(countries)
return
}
// continue with code logic ...
// implementation ...
}
约束对象的类似案例:
function doSomethingWithObject( data: { foo: string; bar: number } | object ){
if(isEmpty(data)){
// $ExpectType {}
data
// following should throw compile error, as data is empty object
data.foo.toUpercase()
return
}
// here we are sure that data is not empty on both runtime and compile time
}
isEmpty 类型保护实现:
export const isEmpty = <T extends AllowedEmptyCheckTypes>(
value: T | AllowedEmptyCheckTypes
): value is Empty<T> => {
if (isBlank(value)) {
return true
}
if (isString(value) || isArray(value)) {
return value.length === 0
}
if (isObject(value)) {
return Object.keys(value).length === 0
}
throw new Error(
`checked value must be type of string | array | object. You provided ${typeof value}`
)
}
定义类型:
type EmptyArray = Array<never>
type Blank = null | undefined | void
/**
* // object collects {} and Array<any> so adding both {} and Array<any> is not needed
* @private
*/
export type AllowedEmptyCheckTypes = Blank | string | object
/**
* Empty mapped type that will cast any AllowedEmptyCheckTypes to empty equivalent
* @private
*/
export type Empty<T extends AllowedEmptyCheckTypes> = T extends string
? ''
: T extends any[]
? EmptyArray
: T extends object ? {} : T extends Blank ? T : never
这有点奇怪,因为它从类型角度正确缩小,但不在 if/else 分支内:
代码可以看这里:https://github.com/Hotell/rex-tils/pull/13/files#diff-a3cdcb321a05315fcfc3309031eab1d8R177
【问题讨论】:
-
我很难遵循这个。您能否将所有相关代码作为代码包含在此处(不是代码图片或代码链接),删除重现问题所需的任何内容,并清楚地指出您的问题所在(您期望什么与您得到什么)?提供minimal reproducible example 对获得有意义的答案大有帮助。
标签: typescript typescript-generics