Typescript typeof 使用场景

21 min read
import databaseConfig from './database.json';
import path from 'path';

interface IDatabaseConfig {
    username: string,
    password: string,
    database: string,
    host: string,
    dialect: "mysql" | "postgres" | "sqlite" | "mariadb" | "mssql" | undefined,
    timezone: string
}

const configs = {
    development: {
        server: {
            host: 'localhost',
            port: 9090
        },
        database: databaseConfig.development as IDatabaseConfig,
        jwt: {
            privateKey: 'kaikeba'
        },
        storage: {
            dir: path.resolve(__dirname, 'attachments'),
            prefix: '/public/attachments'
        }
    }
};

type configs = typeof configs;
type configKeys = keyof configs;

const NODE_ENV = process.env.NODE_ENV as configKeys || 'development';

export default configs[NODE_ENV];

通过 typeof 获取实例类型,再通过keyof获取类型的key的集合