¿Cómo puedo probar si una variable es una matriz de cadena en TypeScript? Algo como esto:
function f(): string {
var a: string[] = ["A", "B", "C"];
if (typeof a === "string[]") {
return "Yes"
}
else {
// returns no as it's 'object'
return "No"
}
};
TypeScript.io aquí: http://typescript.io/k0ZiJzso0Qg/2
Editar: He actualizado el texto para solicitar una prueba para la cadena []. Esto fue solo en el ejemplo de código anteriormente.
typescript
Sean Kearon
fuente
fuente

Respuestas:
No puede probar
string[]en el caso general, pero puede probarArrayfácilmente lo mismo que en JavaScript https://stackoverflow.com/a/767492/390330Si desea específicamente una
stringmatriz, puede hacer algo como:if (Array.isArray(value)) { var somethingIsNotString = false; value.forEach(function(item){ if(typeof item !== 'string'){ somethingIsNotString = true; } }) if(!somethingIsNotString && value.length > 0){ console.log('string[]!'); } }fuente
instanceof Arrayfalla al verificar matrices a través de marcos. PreferirArray.isArray: twitter.com/mgechev/status/1292709820873748480Otra opción es Array.isArray ()
if(! Array.isArray(classNames) ){ classNames = [classNames] }fuente
string.Array.isArray(classNames) && classNames.every(it => typeof it === 'string')Aquí está la solución más concisa hasta ahora:
function isArrayOfStrings(value: any): boolean { return Array.isArray(value) && value.every(item => typeof item === "string"); }Tenga en cuenta que
value.everyvolverátruepara una matriz vacía. Si necesitas regresarfalsepara una matriz vacía, debe agregarvalue.lengtha la cláusula de condición:function isNonEmptyArrayOfStrings(value: any): boolean { return Array.isArray(value) && value.length && value.every(item => typeof item === "string"); }No hay información de tipo en tiempo de ejecución en TypeScript (y no la habrá, consulte Objetivos de diseño de TypeScript> Sin objetivos , 5), por lo que no hay forma de obtener el tipo de una matriz vacía. Para una matriz no vacía, todo lo que puede hacer es verificar el tipo de sus elementos, uno por uno.
fuente
Sé que esto ha sido respondido, pero TypeScript introdujo protectores de tipo: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards
Si tiene un tipo como:
Object[] | string[]y qué hacer algo condicionalmente en función de qué tipo es, puede usar este tipo de protección:function isStringArray(value: any): value is string[] { if (value instanceof Array) { value.forEach(function(item) { // maybe only check first value? if (typeof item !== 'string') { return false } }) return true } return false } function join<T>(value: string[] | T[]) { if (isStringArray(value)) { return value.join(',') // value is string[] here } else { return value.map((x) => x.toString()).join(',') // value is T[] here } }Hay un problema con una matriz vacía que se escribe como
string[], pero eso podría estar bienfuente
return falseen elforEachno tiene ningún efecto.Puede hacerlo fácilmente usando la
Array.prototype.some()siguiente manera.const isStringArray = (test: any[]): boolean => { return Array.isArray(test) && !test.some((value) => typeof value !== 'string') } const myArray = ["A", "B", "C"] console.log(isStringArray(myArray)) // will be log true if string arrayCreo que este enfoque es mejor que otros. Es por eso que estoy publicando esta respuesta.
Actualización sobre el comentario de Sebastian Vittersø
Aquí también puedes usar
Array.prototype.every().const isStringArray = (test: any[]): boolean => { return Array.isArray(test) && test.every((value) => typeof value === 'string') }fuente
test.every(value => typeof value === 'string')Prueba esto:
if (value instanceof Array) { alert('value is Array!'); } else { alert('Not an array'); }fuente
hay un pequeño problema aquí porque el
if (typeof item !== 'string') { return false }no detendrá el foreach. Entonces, la función devolverá verdadero incluso si la matriz no contiene valores de cadena.
Esto parece funcionar para mí:
function isStringArray(value: any): value is number[] { if (Object.prototype.toString.call(value) === '[object Array]') { if (value.length < 1) { return false; } else { return value.every((d: any) => typeof d === 'string'); } } return false; }Saludos Hans
fuente