Javascript 是否将@types中的类型分配给本地代码?
我有一个委托validatorjs的方法,如下所示:Javascript 是否将@types中的类型分配给本地代码?,javascript,typescript,Javascript,Typescript,我有一个委托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'
/**
* 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)
);
}
/**
* 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)
);
}
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: string): boolean {
return (
typeof value === "string" && vjsIsMobilePhone(value, 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
类型
还为此创建了一个。
MobilePhoneLocale
在ValidatorJS
命名空间下声明,导入验证器后即可访问该命名空间。您将其称为ValidatorJS.MobilePhoneLocale
。下面是一个使用ts节点的示例:
> import validator = require("validator")
{}
> function foo(l: ValidatorJS.MobilePhoneLocale): ValidatorJS.MobilePhoneLocale { return l; }
undefined
> foo("en-US")
'en-US'
好的-太棒了-我没有意识到我需要这个部分。谢谢你指出这一点!