This question already has an answer here:
What type is [boolean]?
(1 answer)
Closed 5 years ago.
I have some experience with TypeScript, but one thing just keeps playing on my mind. I know the difference between Array<string> and string[]. I know that the declarations can be used interchangeably, f.e.
export class SomeClass {
someDeclaration: Array<SomeObject>;
otherDeclaration: SomeObject[];
}
But in my work, I faced other declaration structure, namely:
export class OtherClass {
strangeDeclaration: [SomeObject];
}
My question is: Is it correct way to declaring array? Which difference is beetwen this way and other (most popoular) ways? Where does the structure come from?
TypeScript arrays can be written Array<T> or T[] as you suggested.
The other type is a "Tuple". In TS this translated to a index typed array.
E.g. it's a array with a fixed type at the given position.
Example 'tuple array': [Number, String]
Ts Docs explains this very well
Related
This question already has answers here:
How to pass Scala array into Scala vararg method?
(3 answers)
Closed 4 months ago.
I am new to scala, trying to figure out a way to pass the values of array of string as repeated parameter of String in scala.
There is a method which accepts (String,String*) as arguments.
I have array that has the values that i need to pass to the above method, how can i do that ?
Scala requires that you explicitly mark the argument as a variadic argument.
myMethod(firstArg, arrayArg: _*)
The : _*, although it looks like a type annotation, is actually a special bit of syntax you use when you call the method. It says "the thing to my left is an array, and you should pass it (and only it) as the whole variadic argument".
Scala 3 version:
val arr = Array("b", "c")
test("a", arr*)
This question already has answers here:
Typescript primitive types: any difference between the types "number" and "Number" (is TSC case-insensitive)?
(3 answers)
Closed 1 year ago.
In TypeScript, I have an array that I am using like a map to access another array of objects. Here is an extremely simplified example of my code:
var mp : Number[] = [1, 2, 0];
var arr : any[] = ['a', 4, /regex/];
console.log(arr[mp[2]])
However, running this yields:
error TS2538: Type 'Number' cannot be used as an index type.
I've looked elsewhere but the other answers for this type of error don't pertain to something as simple as an array and a Number. If not a Number object, how can I index an array?
TypeScript has two basic number types, the primite number and the Object type Number. Refer to TypeScript: Difference between primitive types for an explanation, but in short:
JavaScript has the notion of primitive types (number, string, etc) and object types (Number, String, etc, which are manifest at runtime). TypeScript types number and Number refer to them, respectively.
In fact, if you run:
console.log(typeof 1);
You will notice that it returns number, not Number.
If you change your map to be an array of number objects, your code will compile without errors.
This question already has answers here:
How to define a regex-matched string type in Typescript?
(9 answers)
Closed 2 years ago.
I am wondering if there is a way to create types that are verified by a function in Typescript/React.
Instead of a 'string' type for example, I would like it to be a regex expression:
interface Verify
{
email: /.+#.*\.com/g;
}
The regex may not work but the concept is of a prop type being a string matching the regex.
A more generalized and useful is to have the input pass through a function to verify it:
interface AcceptableInput
{
input: checkIfInputIsAcceptable(input)
}
let obj: AcceptableInput = { input: "works#working.com" }
Then to check if the input is of the correct type it would check with a function:
function checkIfInputIsAcceptable(input)
{
if(typeof input === "string)
return true;
if(input instanceof AnotherInterface)
return true;
return false;
}
The code does not work, but I hope it exemplifies the concept I am asking about.
I am not sure if this is possible. Any workarounds would also be appreciated.
TypeScript won't really do any complex validation because it's fairly pointless (because you can solve the same issue in different ways, see below) and it heavily complicates the type system. The best way to do something like this is probably via type guards and runtime validation code. (see https://www.typescriptlang.org/docs/handbook/advanced-types.html)
If you're matching against a very basic string pattern then you could also consider looking into template literal types which were added in Typescript 4.1 (see https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html)
I am trying to deserialize an array of JSON objects with GSON. So the simple call:
val arrayOfFoo = gson.fromJson(source, Array<Foo<*>>::class.java>)
should do the trick. But type erasure tells us, that Foo<*> does not exist at runtime, so the error "Only class literals are allowed on the left hand side of a class literal" pops up. Well, so the solution must be:
val arrayOfFoo = gson.fromJson<Array<Foo<*>>>(source, Array::class.java)
Unfortunatelly, now the Kotlin compiler magic - that turns arrays of Wrapper types into primitive arrays - can not be sure what to do and tells us:
"Array class literals require a class type. Please specify one in angle brackets".
But, wait: This is, what did not work a second ago. Using
Array<Foo>::class.java
does not work, too, since now the compiler tells us: "One type argument is expected for Foo".
I personally can not see a way to solve that. Is it impossible to give a class literal of a typed array, which's type also expects a type parameter?
You can get the array class from an array instance, for example either one of
arrayOf<Foo<*>>()::class.java
java.lang.reflect.Array.newInstance(Foo::class.java, 0)::class.java
The basic problem: You need to specify the type of your array. This is done using a TypeToken in Gson.
I hope this helps:
val listType = object : TypeToken<Array<String>>() {}.type
val json = """["1"]"""
val yourClassList :Array<String> = Gson().fromJson(json, listType)
print(yourClassList)
Note that for primitives, it is simpler: Gson().fromJson(json, IntArray::class.java)
This question already has answers here:
How to copy end of the Array in swift?
(6 answers)
Closed 6 years ago.
Swift's implementation of arrays is throwing me for a loop again! (Haw, haw.) All I want is to take an array of arbitrary length and get a new array (or an array slice) from it that has the first element removed.
Why is this so hard?
I just want to be able to do something like this:
let suffix = someArray.suffixFrom(1)
But I can't figure out how to do this. It seems the closest method I've found requires knowing the length of the array, which I don't know because it's computed inline and I really really hate having to split such a simple concept up into a bunch of variables and lines.
Elaboration:
I have a string split by colons (:) and I just want to create a Set containing all the :-delimited components excluding the first one.
So that a string "one:two:three" would return a set containing ["two", "three"]. Since I can create a Set from an array, all I really need is to get the suffix of the array, but I don't know how many components there are because it's inline:
return Set(attributeName?.componentsSeparatedByString(":").suffixFrom(1))
Why does Swift make this so hard?
Edit: Before a bunch of you suggest it, I'm well aware I could extend the array class to do this myself, but I'm writing a framework and I don't want to do that, and I also don't want to have to write a bloody utility function to do something so darned simple.
The CollectionType.dropFirst(_:) does exactly what you need, with the exact syntax you're looking for.
let suffix = someArray.dropFirst(1)