如何区分多个模板文字字符串类型?如果我定义
type UnionTypeExample = `${string}_id` | `${string}_username`
使用
x: UnionTypeExample
how can I check if x
is an id or a username? The temptation is to use some combination of includes()
and "string"
, but this does not work 使用 type guarding.
现在我收到这样的错误
Argument of type '`https://${string}` | `${string}_id`' is not assignable to parameter of type '`https://${string}`'.
Type '`${string}_id`' is not assignable to type '`https://${string}`'.(2345)
下面是代码示例,但这typescript playground example更清楚地显示了错误.
type Url = `https://${string}`;
type ID = `${string}_id`;
type AttributeType = number | Date | Url | ID;
type AttributeLabelProps = {
attribute: number | Date | Url;
}
const handleNumber = (val: Number) => console.log(`${val}: is a number!`)
const handleDate = (val: Date) => console.log(`${val}: is a date!`)
const handleUrl = (val: Url) => console.log(`${val}: is a url!`)
const handleID = (val: ID) => console.log(`${val}: is an id!`)
function AttributeLabel(attribute: AttributeType) {
if (typeof attribute === "number") {
handleNumber(attribute)
}
else if (attribute instanceof Date) {
handleDate(attribute)
}
// What is the correct runtime check to narrow this type from Url | ID to just Url?
else if (typeof attribute === "string" && attribute.startsWith("https://")) {
handleUrl(attribute) // error!
// ~~~~~~~~~
// Argument of type '`https://${string}` | `${string}_id`' is
// not assignable to parameter of type '`https://${string}`'.
}
else {
handleID(attribute)
// ~~~~~~~~~
// Argument of type '`https://${string}` | `${string}_id`' is
// not assignable to parameter of type '`${string}_id`'.
}
};
//This is what I would expect the output to be:
console.log(AttributeLabel(1)) // 1 is a number!
console.log(AttributeLabel(new Date())) // [TODAY] is a date!
console.log(AttributeLabel("https://google.com")) // https://google.com is a url!
console.log(AttributeLabel("dog_id")) // dog_id is an id!