简体   繁体   中英

typescript use object as the type definition

Let's say I have

clients/
  index.ts
  client1.ts
  client2.ts
myApp.ts

// client1.ts
export default class Client1 {}
// client2.ts
export default class Client2 {}

// clients/index.ts
import Client1 from './client1';
import Client2 from './client2';
export { client1, client2 };

Now, I want to use all of clients in myApp and set the type to be based on this, ie

// myApp.ts

import * as clients from './clients';

type Clients = {
 [key in keyof typeof clients]: clients[key];
}

const allClients: Clients = {
  client1: new clients.Client1(),
  client2: new clients.Client2(),
}

The code above is not valid, clients[key]; throws an error about Cannot use namespace 'clients' as a type. but I basically want to be able to import all of the clients, and use that object as the type definition for all my clients. Is this possible?

Why not just create the interface manually? I don't think you're going to be able to create it on the fly like that. And you probably want your types to be static at runtime anyway. They'll be much easier to reason about.

Just define an interface with the clients listed either myApp or where you export them.

import * as clients from './clients';

interface Clients = {
   client1: clients.client1,
   client2: clients.client2,
}

const allClients: Clients = {
  client1: new clients.Client1(),
  client2: new clients.Client2(),
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM