Reputation: 4496
Basically is there a way to extract array values as a string types? Here is the pseudo code:
class A
{
public keys = ['name', 'age']
}
type ArrayKeys = P in A['keys'] // 'name' or 'age'
How to narrow ArrayKeys to be with possible values of A['keys'].
Upvotes: 2
Views: 2023
Reputation: 174957
You will need to assure TypeScript that keys
will not change by adding an as const
cast (otherwise, TypeScript will just assume it's a string array), note that this will make TypeScript enforce this. You will not be able to change the array.
After that, it's fairly simple:
class A
{
public keys = ['name', 'age'] as const
}
type ArrayKeys = A['keys'][number];
The [number]
part is the "accessing" of the array's value. (Array<T>)[number]
will always be T
.
Upvotes: 10
Reputation: 1074148
I don't think you can literally do that, since of course types are a static compile-time feature and arrays are a dynamic runtime feature. ...unless you add const
as Madara Uchiha shows us.
But you could use a string enum instead of an array, and then get its values to fill in the array.
enum ArrayKeys {
name, age
}
class A {
public keys = Object.keys(ArrayKeys).filter(key => isNaN(Number(key)));
}
This also has the advantage of providing ArrayKeys.name
and ArrayKeys.age
as enum values.
Upvotes: 2