TypeORM 原始实体的类型:CamelToSnake / ValueOf 精确匹配 / 属性方法推理

问题描述 投票:0回答:1

总结:在 TypeORM 中生成原始返回类型的类型

您好,我正在使用 TypeORM,并且有一个关于处理原始返回类型的问题。使用 getRawOne 和 getRawMany 函数时,返回包括由类名和属性组成的字符串,这些字符串用下划线('_')连接。

例如:

export class TestUser {
    id: number;
    name: string;
    verified: boolean;
}
const userRepository = getRepository(TestUser);

// getRawOne is not support type. just return any type. I want to disclose this return type.
const loaedRawTestUser = await userRepository.createQueryBuilder('testUser')
    .addSelect('COUNT(*()', 'myAliasForAllUserCount')
    .getRawOne();

/**
 * {
 *   testUser_id: number;
 *   testUser_name: string;
 *   testUser_verified: boolean;
 * }
 */
console.log(loaedRawUser);

本期分为三部分:

  • 将camelCase转换为snake_case。
  • 推断返回字符串的组成的类名。
  • 转换后的属性(实体键)的精确值匹配。

第一部分已解决。

我已经实现了从camelCase到snake_case类型推断器,如下所示:

export type CamelCaseToSnakeCase<
    T extends string,
    Joiner extends '' | '_' = ''
> = T extends `${infer Character}${infer Rest}`
    ? Character extends Uppercase<Character>
        ? `${Joiner}${Lowercase<Character>}${CamelCaseToSnakeCase<Rest, '_'>}`
        : `${Character}${CamelCaseToSnakeCase<Rest, '_'>}`
    : '';

有什么办法吗?


如果可以的话还有其他要求。

当 TestUser 类有这样的方法时:

export class TestUser {
    id: number;
    name: string;
    verified: boolean;
    
    getNameIfVerified(): {
        return this.verified ? this.name : 'not verified'
    }
}

const typeormRawColumTestSample: Partial<TypeORMRawColumns<TestUser, 'TestUser'>> = {
    testUser_id: 1,
    //  when testUser_id: '1' should be error.
    testUser__get_name_if_verified // should be error.
}

如何从 TypeScript 中的类型中排除方法

typescript typeorm type-inference
1个回答
0
投票

我已经部分解决了第二个问题,但还没有完全解决。

/**
 * Not yet typescript is not support inferring class name from Type T.
 * So, I regard programmer must input entity class name as hardcoding. 
 */
export type TypeORMRawColumns<
    Entity,
    EntityClassName extends string,
    ConvertedPropertyAsSnake = `${Uncapitalize<EntityClassName>}_${CamelCaseToSnakeCase<
        Extract<keyof Entity, string>
    >}`,
    ValueType = Entity[keyof Entity]
> = {
    [key in Extract<ConvertedPropertyAsSnake, string>]: ValueType;
};

// Second parameter is hard coded for class name.
const test1: TypeORMRawColumns<TestUser, 'TestUser'> = {
    testUser_id: 1,
    testUser_name: 'john',
    testUser_verified: true
};

// But by union type, it is not safe from other property type.
// Expected error but it is not.
const test2: TypeORMRawColumns<TestUser, 'TestUser'> = {
    testUser_id: 'it is not type-safe. Because of ValueOf is union type of Entity properties.',
    // like number | string | boolean
    testUser_name: 'john',
    testUser_verified: true
};
© www.soinside.com 2019 - 2024. All rights reserved.