• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Create Generic and Non-Generic Types in TypeScript?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction


In TypeScript, creating both generic and non-generic versions of a class provides flexibility in how data is structured and manipulated. The question at hand is how to achieve this with the ServiceResponse class by defining a non-generic object appropriately alongside a generic one. This article will cover how to properly implement such a solution, while addressing common concerns like handling properties when using generics.

Understanding Generics and Non-Generics in TypeScript


Before diving into the implementation, let's take a moment to understand why you might need both generic and non-generic classes in TypeScript. Generics allow you to create reusable components that can work with different types, while non-generic classes are often used when a specific type is not required or when an implementation is kept simple.

In this case, the goal is to define a class ServiceResponse<T> such that:

  • When using the generic version, the property result must be defined.
  • When using the non-generic version, it should also be clear that result cannot exist or should not be defined.
Defining a Generic ServiceResponse Class


The basic structure for the ServiceResponse class looks like this:

export class ServiceResponse<T = void> {
result?: T;
}


Here, T is a generic type with a default of void. The key aspect of this class is that result is optional. This allows for flexibility when you don’t require a concrete value for certain cases, but it may lead to scenarios where you need to verify result’s existence. To illustrate how this works:

Example of a Generic ServiceResponse


Here’s how you can utilize the generic class:

const respGeneric: ServiceResponse<string> = { result: "Success" };
console.log(respGeneric.result); // Output: Success

Handling the Non-Generic Version


Now, the challenge arises with defining how to adequately implement a non-generic version. You want to avoid having to set result as optional. A simple trick is to leverage another type union or an interface. Here’s a way to achieve this:

Using a Dummy Type to Represent No Content


We will need a base interface and extend it:

interface BaseResponse {
result?: never; // Use never to indicate absence
}

export class ServiceResponse<T = void> extends BaseResponse {
result?: T;
}


This way, if you decide not to specify the generic type, the absence of content is enforced:

Instantiating Non-Generic ServiceResponse


const respNonGeneric: ServiceResponse = {}; // Valid as it adheres to the BaseResponse interface
console.log(respNonGeneric); // Output: {}

Why Not Use Optional Properties?


While options are available, such as defining result as optional with result?, it compromises the integrity of your type design. If result is optional, the consumer must constantly check if result exists, which can introduce runtime errors. Hence, having it as never provides clarity and clean enforcement of types.

Frequently Asked Questions (FAQ)

1. How do I handle methods that interact with a non-generic ServiceResponse?


Implement methods in the generic class that check for the presence of result and return meaningful messages or actions based on its state.

2. Is it possible to create multiple types of non-generic responses without adding complexity?


Yes, by following the structural type system in TypeScript, you can create multiple base types that extend the ServiceResponse class, allowing for different types of non-generic implementations.

3. Can I use null for result?


Using null is an option, but to prevent misuse, it's recommended to adhere to never to enforce expectations more solidly when defining service responses.

Conclusion


By effectively utilizing TypeScript’s typing system, you can create both generic and non-generic versions of a service response that are clean, maintainable, and fulfill the necessary use cases. Utilizing never for unassigned state will keep your implementation clear and concise, allowing for better type safety and fewer runtime checks. This approach makes your code easier to work with and enhances its robustness against common pitfalls inherent in type handling.

By now, you should have a solid understanding of how to structure your TypeScript service responses while effectively working with generics and non-generics. Happy coding!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу