Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

Monday, March 17, 2025

But can it run DOOM?

I barely repost news from elsewhere but this time this is extremely impressive.

It was announced that Dimitri Mitropoulos from the TypeScript team was able to build a WebAssembly interpreter in the TypeScript typesystem and then make it run DOOM, still inside the type system. Well, not quite "run", just render the first frame which took 12 days.

Anyway, it's inspiring to hear such news. Congratulations to the team!

Friday, August 26, 2022

TypeScript puzzle No.2 (easy)

Consider following code

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
foo.bar()

Now consider that for some reason we want to include a type assertion, rather than just foo we want foo as Foo.

class Foo {
  bar() {
    return 1
  }
}

const foo = new Foo
(foo as Foo).bar()

Surprisingly, this one doesn't compile, the error points to the last line and says

Block-scoped variable 'foo' used before its declaration

As always, your goal is to explain the unexpected behavior here.

Monday, August 22, 2022

TypeScript's Conditional Type Operator example

We all like good examples, examples which, when seen, make us grasp new ideas easier. I believe the notion of Conditional Types in TypeScript is often demonstrated in a way that makes you wonder what's the real purpose of it. Let's just have yet another example that could be useful here.

Let's start with a function type, it could be a type of a custom function or a built in function.

// a custom function
function foo( s: string, n: number, b: boolean | symbol) : void {

}
type FooType = typeof foo;
// FooType = (s: string, n: number, b: boolean | symbol) => void

// the built in function, Array.prototype.slice
type ArraySliceType = typeof Array['prototype']['slice'];
// ArraySliceType = (start?: number | undefined, end?: number | undefined) => any[]
The two function types have a different number of parameters but with the TypeScript's type system, we can write an auxiliary type that just picks a type of specific parameter.

This is where the actual example begins. The initial part of the example is based on a code presented in Programming TypeScript by B. Cherny. Let's start with a type that picks a parameter that comes, like, second on the list of parameters.

type SecondArg<F> = F extends (a: any, b: infer B, ...c: any ) => any ? B : never;
Let's comment that. The SecondArg type is a generic type that expects a single generic parameter, F. This single generic parameter type is checked to be a function (the F extends ... part) and depending on the test, the conditional operator either returns an inferred type of the second argument (infer B) or fails (never).

Let's test this

type SecondArgString = SecondArg<string>;
// never
type SecondArgFoo = SecondArg<FooType>;
// number
type SecondArgArraySlice = SecondArg<ArraySliceType>;
// number | undefined
This works great and to me - it's enough to demonstrate how useful the ? : conditional operator is. Using this technique we can pick a type of a specific argument of specific function type, which, as far as I know, is not possible in languages like, say, C# or Java. In C#, if there's a function and the second argument of the function is, say, int and you have to declare a variable of this type, you have to know this type in advance to even start writing code.

But, this example can easily be pushed forward, why just pick a specific, second parameter? Why not write a generic type that picks the argument we want, first, second, third? Let's go beyond the original example from the book.

The question is, can numbers (parameter indexes) can be arguments of generic types?

The answer is, sure, it's TypeScript, literals can be types. Remember the part of the TypeScript tutorial when you learn that a string 'foo' can also be a type that is just a subtype of string? Well, 5 can be a type that's just a subtype of number.

The only small technical issue is that our new generic type needs two generic arguments and we need constraints on both of them which the ? : operator doesn't support directly (or I don't know how to do it :).

The first approach involves nesting the ? : operator so that the nested part introduces the constraint on the second argument.

type NThArg<F, N> = 
    F extends (...c: infer C) => any 
    ? (N extends number ? C[N] : never ) 
    : never;  
  
Please take a while to compare this new type to the previous one. As you can see, the parameter list is expressed in a more concise way, we don't need to introduce specific parameters, instead we hide them all under the spread (...) operator. But the other generic parameter, N is constrained to be a number (the N extends a number part) so that it can be used to just index the signature type (the C[N]) part.

If nesting the conditional type operator bothers you as much as it bothers me, there's another version

type NThArg2<F, N extends number> = 
    F extends (...c: infer C) => any 
    ? C[N]
    : never;  
  
This time there's no nesting of the conditional operator. Instead, the constraint on N is expressed directly in type signature which works here as the constraint on N doesn't really invole anything fancy (no need for conditionals, infer, etc.)

Both operators work, please take your time to play around

type FooTypeNth10  = NThArg<FooType, 0>
// string
type FooTypeNth11  = NThArg<FooType, 1>
// number
type NThArgSlice = NThArg<ArraySliceType, 1>;
// number | undefined

type FooTypeNth2  = NThArg2<FooType, 1>
// number
type NThArgSlice2 = NThArg2<ArraySliceType, 1>;
// number | undefined  
  

And just by the way, did you know that TypeScript's type system is Turing Complete (please also take a look here and here and here)? This basically means that we could write actual programs using types only and results would be computed by the compiler during compilation. Please check the linked article to find few possible ways this could be used (and no, it's not quite useful, you wouldn't like to write code that runs on your type system).

Happy coding.

Thursday, August 11, 2022

Node.js + Express + TypeScript (ts-node reloaded)

This is a short follow up to one of my previous posts, the Node.js + Express + TypeScript where a tiny tutorial on writing node.js node with TypeScript was discussed.
This time I'd like to introduce the ts-node which basically wraps the TypeScript execution in a single pipeline so that there's no need to precompile the TypeScript to JavaScript.
One of ways to use the ts-node is to install it globally and run the TypeScript code with
ts-node app.ts
Note only that the tsconfig.json has to be present, just to configure TypeScript options.
However, to also be able to debug the TypeScript from the Visual Studio Code and still use the ts-node to execute the code, install the ts-node locally and create a .vscode/launch.json section
{
    "name": "ts-node",
    "type": "node",
    "request": "launch",
    "args": ["${workspaceFolder}\\app.ts"],
    "runtimeArgs": ["-r", "ts-node/register"],
    "cwd": "${workspaceRoot}",
}
A tiny code to test this
// app.ts
import * as http from 'http';
import express, { Express, Request, Response } from 'express';

var app: Express = express();

app.get('/', (req: Request, res: Response) => {
    res.write('hello world');
    res.end();
});

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );

Monday, April 25, 2022

Node.js + Express + TypeScript

The Node.js + Express + Javascript is a great platform and this short tutorial shows how to add TypeScript to the picture.

Start with installing TypeScript compiler globally

npm install typescript -g
so that whenever you invoke tsc from the command line, the compiler follows your tsconfig.json and does its job. Then add the tsconfig.json
{
    "compilerOptions": {
        "lib": [
            "es2021", "DOM"
        ],
        "module": "commonjs",
        "target": "es2021",
        "strict": true,
        "esModuleInterop": true,
        "sourceMap": true                
    }
}
Note that we specifically ask the module subsystem to translate TypeScript's export/imports into node.js commonjs modules. We also turn on the esModuleInterop flag for better node.js compatibility.

Now install some typings for node and express (other typings should possibly also be installed, depending on what packages you are going to use.

npm i --save-dev @types/node
npm i --save-dev @types/express

Create the app.ts file, which will be the starting point of the app and add .vscode/launch.json with

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\app.ts",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}
Note how the entry point (program) is set up here. Because the Typescript compiler will generate source maps, you would be able to run&debug the Typescript code.

Writing Typescript is easy now. Create an example express app

import * as http from 'http';
import express from 'express';

var app = express();

app.get('/', (req, res) => {
    res.write('hello world');
    res.end();
});

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );
Note how express is imported and how a library module (http) is imported - in both cases, there's the full intellisense support in VS Code as well as the support from the Typescript compiler.

To compile the code just invoke

tsc
once. To run the compiler in the watch mode:
tsc --watch

To show how TS modules work, create a simple module, m.ts with

class Example {
    DoWork( s: string ) : string {
        return s + ' from Example';
    }
}

export default Example;
and import it in the app.ts
import * as http from 'http';
import express from 'express';
import Example from './m';

var app = express();

app.get('/', (req, res) => {

    let e = new Example();

    res.write(e.DoWork('hello world'));
    res.end();
});

var server = http.createServer(app)

server.listen(3000);

console.log( 'started' );
Note how m.ts is compiled to m.js and also note how m.js is imported in the app.js (compiled from app.ts).

Friday, October 22, 2021

Visual Studio Code + TypeScript + React - how to start in 10 minutes (fall 2021 tutorial)

Just a short tutorial on how to start your adventure with TypeScript + React with Visual Studio Code. Without further ado:
Install node.js. Install Visual Studio Code.
Create an empty folder. Go to it and run VSC from there from the OS shell
code .
When in VSC, open the terminal and work from the terminal rather than the OS shell
npm init -y
npm install webpack webpack-cli
npm install typescript ts-loader
npm install react react-dom
npm install @types/react @types/react-dom
This will create package.json and install your dependencies.
At the root of your app create two files, tsconfig.json

{
    "compilerOptions": {
        "allowJs": false,
        "baseUrl": "./",
        "jsx": "react",
        "declaration": false,
        "esModuleInterop": true,
        "lib": ["ES6", "DOM"],
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": true,
        "outDir": "./dist/",
        "paths": {
        "@/*": ["src/*"]
        },
        "sourceMap": true,
        "target": "ES6"
    }
}
and webpack.config.js
    const path = require('path');
    const TerserPlugin = require("terser-webpack-plugin");

    module.exports = {
    //mode: 'production',
    mode: 'development',
    target: ['web','es6'],
    entry: {
        'index': './src/index.tsx'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    devtool: 'source-map',
    module: {
        rules: [{
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
        }, ],
    },
    externals: {
        // Use external version of React
        //'react': 'React',
        //'react-dom': 'ReactDOM'
    },
    resolve: {
        // https://getfrontend.tips/shorten-import-paths-in-webpack/
        alias: {
        // Assume that the `src` folder is located at the root folder
        '@': path.join(__dirname, 'src'),
        },
        extensions: ['.tsx', '.ts', '.js'],
    },
    optimization: {
        minimize: false, // true/false
        minimizer: [
        new TerserPlugin({
            extractComments: false,
            terserOptions: {
            format: {
                comments: false,
            },
            },
        })
        ],
    },
    };
There are few options in the webpack's configuration file that can be further changed, pay close attention to mode and minimize.
Now create two empty folders, src and dist, the first is where your source code goes, the second is where webpack will store its output.
Now create two TypeScript files. First is your entry point, index.tsx
import React from 'react';
import ReactDOM from 'react-dom';

import App from '@/app';

/**
 * Entry point
 */
class Program {
    
    Main() {

        var app = (
                <App />
        );

        ReactDOM.render(app, document.getElementById('root'));
    }
}

new Program().Main();
or using the new API that replaces ReactDOM.render
import React from 'react';
import { createRoot } from 'react-dom/client';

import App from '@/app';

/**
 * Entry point
 */
class Program {
    
    Main() {

        const app = (
            <React.StrictMode>
                <App />
            </React.StrictMode>
        );            

        const root = createRoot(document.getElementById('root'));

        root.render( app );    
    }
}

new Program().Main();
Second is your app's component, app.tsx
import React from 'react';

const App = () => {

  return <>  
    Hello world from React & Typescript
  </>
};

export default App;
The general rule here is that
  • if a module is a pure TypeScript, your file can have *.ts extension
  • if a module should contain JSX code, your file should have *.tsx extension
Modules are imported/exported between both without any restrictions.
Now add the last file, app.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script defer src="/dist/index.js"></script>
    <style>
    * , *:before, *:after { 
         box-sizing:border-box; 
    }
    html {
        background-color: rgb(234, 238, 243);
    }

    </style>
</head>
<body>    
    <div id="root"></div>
</body>
</html>
What you should have right now is
Now just invoke
webpack
(this assumes webpack is available globally, if not, npm-install both webpack and webpack-cli as global modules:
npm install -g webpack webpack-cli
) and the application will be built and the output, dist/index.js will be created. This is a single file bundle and it can be further optimized by switching mode to production in the config, as well as turning on minimization.
To test the app, install and run a simple HTTP server, e.g. live-server
npm install -g live-server
live-server
and add a launch configuration in VSC
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080/app.html",
            "webRoot": "${workspaceFolder}"
        }
    ]
}
Congratulations, you can start your app with F5 from within VSC, put breakpoints in your TypeScript and debug your code and continue work on your first great app. Happy coding!

Thursday, August 26, 2021

TypeScript puzzle No.1 (intermediate)

There's a callable type definition
type Callable = {
    description: string;
    (a: string): string;
}
It's pretty obvious that if given an instance of the type, one can just call it:
function CallableClient( c: Callable, s: string ): string {
    return c(s);
}
The question is however, how to create instance of the type so that it's both callable and has the string property and the creation is strongly typed (doesn't involve any type). Formally, your task is to implement the factory method that takes a function, a description and composes them:
function F2Factory( f: (a:string) => string, description: string ): Callable {
    return ...; // ??
}

This is actually pretty interesting so here's goes the story. There are two possible approaches I am aware of.

First approach involves a const that is further expanded with an attribute:

const c : Callable = (s: string) => s;
c.description = "foo";

// c is correctly of Callable type and can be called
Note that it only work when the variable is declared as const, doesn't work with var/let. This should be enough to provide the implementation of the F2Factory

Second approach involves Object.assign which is typed as Object.assign<T, U>( t: T, u: U ) : T & U. It's great as it looks like it could just combine two objects and return a new object that act as both. Of course then, this works

function F2Factory( f: (a:string) => string, description: string ): Callable {
  return Object.assign(f, { description });
}

const c = F2Factory( (s: string) => s, 'foo' );

console.log( c('bar') );
console.log( c.description );
Note, however, that there's a caveat here. The Object.assign basically duplicates attributes of the source to the target. However, a callable object (a function) doesn't have any properties that can be duplicated to another object so that the other object would become callable too. This doesn't work then:
function F2Factory( f: (a:string) => string, description: string ): Callable {
  return Object.assign({ description }, f);
}

const c = F2Factory( (s: string) => s, 'foo' );

console.log( c('bar') );
console.log( c.description );
This could be surprising for someone, it doesn't work even though it types correctly!

The reason here is that for the typescript compiler, using Object.assign to combine a function and an object in any order produces the same output type. However, for the Javascript engine that actually runs the code, adding description to a function works but trying to duplicate callability to a simple object { description } by no means makes this object callable.

This discrepancy between the Typescript compiler and the Javascript runtime would be even more clear if we consider a type that combines two callable members

type Callable2 = {
    (a: number): number;
    (a: string): string;
}
This time the Object.assign will never yield expected output - it can't combine two functions to create yet another function that correctly handles input argument type.