'不可分配给类型 never'使用类型谓词后
我正在尝试结合 创建强类型的技术带有类型谓词的字符串但失败,如以下代码所示:
错误是TS2339:属性'substr'在类型'never'上不存在
,但解决这个问题正是工厂函数应该确保的:
export function isShortDateTimeWithSpaceDelimiter(
datetime: string | ShortDateTimeWithSpaceDelimiter
): datetime is ShortDateTimeWithSpaceDelimiter {
return DateTime.fromFormat(datetime, FORMAT_ISO_DATE_SPACE_DATE_TIME).isValid;
}
export function toShortDateTimeWithSpaceDelimiter(
datetime: string
): ShortDateTimeWithSpaceDelimiter {
if (isShortDateTimeWithSpaceDelimiter(datetime)) return datetime;
throw new TypeError("Not a ShortDateTimeWithSpaceDelimiter");
}
因为TS假设工厂的返回类型是never
,我想这没有按我的预期工作......我错过了什么?
类型定义如下所示:
// https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/
enum LocalDateTimeWithSpaceDelimiterBrand {}
/** Minute granularity: "yyyy-MM-dd hh:mm" */
export type ShortDateTimeWithSpaceDelimiter = string & LocalDateTimeWithSpaceDelimiterBrand;
I am trying to combine a technique for creating strongly typed strings with type predicates but failing, as the following bit of code shows:
The error is TS2339: Property 'substr' does not exist on type 'never'
, but fixing this is exactly what the factory function should have ensured:
export function isShortDateTimeWithSpaceDelimiter(
datetime: string | ShortDateTimeWithSpaceDelimiter
): datetime is ShortDateTimeWithSpaceDelimiter {
return DateTime.fromFormat(datetime, FORMAT_ISO_DATE_SPACE_DATE_TIME).isValid;
}
export function toShortDateTimeWithSpaceDelimiter(
datetime: string
): ShortDateTimeWithSpaceDelimiter {
if (isShortDateTimeWithSpaceDelimiter(datetime)) return datetime;
throw new TypeError("Not a ShortDateTimeWithSpaceDelimiter");
}
Since TS assumes the return type from the factory is never
, I guess this is not working as I had intended ... What am I missing?
The type definitions look like this:
// https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/
enum LocalDateTimeWithSpaceDelimiterBrand {}
/** Minute granularity: "yyyy-MM-dd hh:mm" */
export type ShortDateTimeWithSpaceDelimiter = string & LocalDateTimeWithSpaceDelimiterBrand;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
The type
ShortDateTimeWithSpaceDelimiter
is really just an alias fornever
, so it's practically useless and isn't as helpful as it should be when defining a different "type" of string.There is also a playground example of nominal typing: playground
So here you could use
string & { __brand: "ShortDateTimeWithSpaceDelimiter" }
.However I do suggest throwing all of this away altogether and stick with the simple
string
. Why is all of this necessary? Overkill occurs when types start being defined by code and act like code! Types should influence the design and implementation, not the other way around.