我有一个委托给validatorjs的方法,如下所示:
/**
* Checks if the string is a mobile phone number (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK',
* 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ']).
* If given value is not a string, then it returns false.
*/
export function isMobilePhone(value: string, locale: string): boolean {
return (
typeof value === "string" && vjsIsMobilePhone(value, locale)
);
}
VSCode为
locale
参数呈现以下错误:[ts]类型'string'的参数不能分配给'MobilePhoneLocale'类型的参数。
(参数)语言环境:字符串
MobilePhoneLocale
类型来自@types/validator
。如果我将MobilePhoneLocale
分配给locale
(而不是使用字符串),则该方法如下所示: /**
* Checks if the string is a mobile phone number (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK',
* 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ']).
* If given value is not a string, then it returns false.
*/
export function isMobilePhone(value: string, locale: MobilePhoneLocale): boolean {
return (
typeof value === "string" && vjsIsMobilePhone(value, locale)
);
}
但是现在ts会出现此错误:
[ts]找不到名称'MobilePhoneLocale
上述功能应如何实现
locale
的类型?还为此创建了一个@types/validator github issue。
最佳答案
MobilePhoneLocale
在ValidatorJS
命名空间下声明,导入validator
后即可访问。您将其称为ValidatorJS.MobilePhoneLocale
。这是使用ts-node
的示例:
> import validator = require("validator")
{}
> function foo(l: ValidatorJS.MobilePhoneLocale): ValidatorJS.MobilePhoneLocale { return l; }
undefined
> foo("en-US")
'en-US'