Branding, UI Design Programming / 05 February 2024 / by Md Shahidul Islam

TypeScript Tutorial: A Comprehensive Guide

TypeScript Tutorial: A Comprehensive Guide

Chapter 1: Introduction to TypeScript

What is TypeScript?

TypeScript is a superset of JavaScript, developed and maintained by Microsoft. It is a statically-typed programming language that aims to improve the development experience and increase the productivity of developers working on large-scale applications.

TypeScript adds optional static typing to JavaScript, which means that you can specify the data types of variables, function parameters, and return values. This helps catch errors at compile-time, rather than at runtime, making your code more robust and easier to maintain.

Why Use TypeScript?

There are several reasons why you might want to use TypeScript over plain JavaScript:

  1. Static Typing: TypeScript’s static typing helps catch errors at compile-time, making your code more reliable and less prone to runtime errors.

  2. Better Tooling: TypeScript integrates well with popular IDEs like Visual Studio Code, providing features like auto-completion, code navigation, and refactoring, which can greatly improve developer productivity.

  3. Scalability: TypeScript is particularly useful for large-scale applications, where the codebase can become complex and difficult to manage. The static typing and tooling features of TypeScript help maintain code quality and facilitate collaboration among large development teams.

  4. Future-Proof: TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code. This ensures that you can gradually migrate your existing JavaScript codebase to TypeScript, without having to rewrite everything from scratch.

Getting Started with TypeScript

To get started with TypeScript, you’ll need to have Node.js and npm (the Node.js package manager) installed on your system. Once you have these, you can install the TypeScript compiler globally using the following command:

npm install -g typescript

Now, you can create a new TypeScript file (typically with the .ts extension) and start writing your code. For example, create a file named hello.ts with the following content:

function greet(name: string) {
  console.log(`Hello, ${name}!`);
}

greet('TypeScript');

To compile this TypeScript file to JavaScript, run the following command in your terminal:

tsc hello.ts

This will generate a hello.js file, which you can then run using Node.js:

node hello.js

You should see the output: Hello, TypeScript!

In this first chapter, you’ve learned what TypeScript is, why you might want to use it, and how to get started with the language. In the next chapter, we’ll dive deeper into the core features of TypeScript, such as its type system and type annotations.

import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:test/test.dart';

void main() {
  group('ChatGPT API Client', () {
    test('sends a successful chat completion request', () async {
      final dio = Dio(BaseOptions(
        baseUrl: 'http://localhost:3040/v1',
        headers: {
          'Content-Type': 'application/json',
        },
      ));

      final messages = [
        {'role': 'user', 'content': 'Hello, how are you?'},
      ];

      final response = await dio.post(
        '/chat/completions',
        data: {
          'messages': messages,
          'stream': false,
        },
      );

      expect(response.statusCode, equals(200));

      final responseBody = response.data;
      expect(responseBody, containsPair('object', 'chat.completion'));
      expect(responseBody['choices'], isNotEmpty);
      expect(responseBody['choices'].first['message']['content'], isNotEmpty);
    });

    test('sends a successful streaming chat completion request', () async {
      final dio = Dio(BaseOptions(
        baseUrl: 'http://localhost:3040/v1',
        headers: {
          'Content-Type': 'application/json',
        },
        responseType: ResponseType.stream,
      ));

      final messages = [
        {'role': 'user', 'content': 'Can you tell me a joke?'},
      ];

      final response = await dio.post(
        '/chat/completions',
        data: {
          'messages': messages,
          'stream': true,
        },
      );

      expect(response.statusCode, equals(200));
      expect(response.headers.value(Headers.contentTypeHeader), equals('text/event-stream'));

      final responseLines = LineSplitter.split(await response.data.join()).toList();
      expect(responseLines, isNotEmpty);
      expect(responseLines.any((line) => line.contains('"object":"chat.completion.chunk"')), isTrue);
    });

    test('handles an invalid request', () async {
      final dio = Dio(BaseOptions(
        baseUrl: 'http://localhost:3040/v1',
        headers: {
          'Content-Type': 'application/json',
        },
      ));

      try {
        await dio.post(
          '/chat/completions',
          data: {
            'messages': [],
          },
        );
      } catch (e) {
        if (e is DioError) {
          expect(e.response?.statusCode, equals(500));

          final responseBody = e.response?.data;
          expect(responseBody, containsPair('status', false));
          expect(responseBody?['error'], containsPair('message', 'An error happened, please make sure your request is SFW, or use a jailbreak to bypass the filter.'));
          expect(responseBody?['error'], containsPair('type', 'invalid_request_error'));
        } else {
          fail('Unexpected error: $e');
        }
      }
    });
  });
}
Tags:
Comments