#How to get keys of values of an interface
1 messages · Page 1 of 1 (latest)
!screenshot
Rather than screenshots, please provide either code formatted as:
```ts
// code here
```
Or even better, as an example on the TypeScript playground that is as simple as possible and reproduces the issue. This makes it easier to help you and increases the chances of getting an answer.
Preview:```ts
// types/Database.ts
export interface MainDB {
guild: { id: string; prefix: string };
}
export interface TestDB {
[key: string]: object;
}
export default interface Databases {
main: MainDB;
test: TestDB;
}
// classes/Database.ts
import { Document, MongoClient, ServerApiVersion } from "mongodb";
...```
Preview:```ts
...
on<
DBName extends keyof Databases,
CName extends keyof Databases[DBName] & string
(dbName: DBName, name: CName) {
return this.client.db(dbName).collection(name)
}
...```
like the above snippet?
yes, but now how can i do this
Preview:```ts
export interface MainDB {
guild: {id: string; prefix: string}
}
export interface TestDB {
[key: string]: object
}
export default interface Databases {
main: MainDB
test: TestDB
}
import {
Document,
MongoClient,
ServerApiVersion,
} from "mongodb"
...```
@calm eagle
Preview:```ts
import {
Document,
MongoClient,
ServerApiVersion,
} from "mongodb"
export type MainDB = {
guild: {id: string; prefix: string} & Document
[k: string]: Document
}
export type TestDB = Record<string, Document>
type Databases = {
main: Mai
...```
I don't want to use any name in main db
It should only have the collection i defined
only main db?
All db other than "test"
okay
Preview:ts ... return this.client .db(dbName) .collection(name) as Databases[DBName][CName] ...
like this
Preview:```ts
...
public getCollection<
DBName extends keyof Databases,
CName extends keyof Databases[DBName] & string
(dbName: DBName, name: CName) {
return this.client
.db(dbName)
.collection(name) as Collection<
Databases[DBName][CName]
}
}
new Database("").getCollection("main", "guild")```
it should return the value inside Collection<>
Cuz later findOne would use that type from that
oh, I didn't see the collection
btw, something like that not possible?
hmm... because that's conditional type with extends keyword is not in the interface context
How else can I fix it
Ohh
What does & do btw
Learn TypeScript if you have a background in functional programming
The name is intersection, but it doesn't behave like an intersection operator in math
But anyways
!solved
!resolved
u can use name as string