Is it possible to have a keyof an object plus any string (for autocomplete) but then have a way to extract only the keys that were defined?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
1 messages · Page 1 of 1 (latest)
Is it possible to have a keyof an object plus any string (for autocomplete) but then have a way to extract only the keys that were defined?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@full remnant Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
const obj = {
firstName: "first",
lastName: "last",
}
type Obj = typeof obj
type KeysAndString<T> = {
key: (string & {}) | keyof T
}
const anotherObj: KeysAndString<Obj>[] = [
{
key: "firstName", // autocomplete OK
},
{
key: "foo", // allows other non-keys
...```
this is a bit verbose, but i think it does what you want:
Preview:```ts
const obj = {
firstName: 'first',
lastName: 'last'
}
type Obj = typeof obj;
type KeysAndString<T> = {
key: (string & {}) | keyof T
};
const anotherObj = [{
key: 'firstName' // autocomplete OK
},
{
key: 'foo' // allows other non-keys
}] as const satisfies readonly KeysAndString<Obj>[];
...```
a key point is the usage of const anotherObj = ... satisfies X instead of const anotherObj: X = .... the latter throws away any information beyond what X represents, so there's no way later on to figure out that 'foo' was given as a key while 'name' wasn't
What about?
type Slots<T extends readonly { key: string }[]> = {
[K in T[number]['key'] as `item-${K}`]: Obj
}
ah yeah much better. i tried something like that initially but at that point i was under the mistaken impression that they wanted the values to be specific to the array element instead of always Obj
Verbose is fine! I think this will work
Thank you
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@full remnant Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
import {Ref, computed, ref} from "vue"
export type ColumnDef<T> = {
// eslint-disable-next-line @typescript-eslint/ban-types
key: (string & {}) | keyof T
title: string
}
type TableOptions<T> = {
data: Ref<T[] | undefined>
columns: ColumnDef<T>[
...```