How to get only keys as autocomplete from a interface ?
<code>interface IUser {
id: string;
firstname: string;
lastname: string;
}
</code>
<code>interface IUser {
id: string;
firstname: string;
lastname: string;
}
</code>
interface IUser {
id: string;
firstname: string;
lastname: string;
}
€:
I have here an array and want to add my keys in there:
<code> let allowedSortIds = [
'id',
'firstname',
'lastname',
]
</code>
<code> let allowedSortIds = [
'id',
'firstname',
'lastname',
]
</code>
let allowedSortIds = [
'id',
'firstname',
'lastname',
]
5
If you want allowedSortIds
to be an array that only accepts values which are keys of the IUser
interface, then you can annotate it as Array<keyof IUser>
or the equivalent (keyof IUser)[]
, using the keyof
type operator to query IUser
for the union of the literal types of its keys. Once TypeScript knows that the elements of allowedSortIds
can only be keyof IUser
, then IntelliSense will auto-suggest and auto-complete these types for you also:
<code>let allowedSortIds: (keyof IUser)[] = [
// ^
// 🔧 "firstname"
// 🔧 "id"
// 🔧 "lastname"
]
</code>
<code>let allowedSortIds: (keyof IUser)[] = [
// ^
// 🔧 "firstname"
// 🔧 "id"
// 🔧 "lastname"
]
</code>
let allowedSortIds: (keyof IUser)[] = [
// ^
// 🔧 "firstname"
// 🔧 "id"
// 🔧 "lastname"
]
Playground link to code