TypeScript - expression of types / constructors compared to type instances

Types

We could express the use of a type alias, which we expect the type to be passed as an argument, for example:

type Type<T> = {
    readonly prototype: T
}

function getTypeArg<T>(t: Type<T>): void {
    ...
}

This fails because it 123is primitive / instance and therefore does not have a prototype property.

getTypeArg(123);

This passes because it is a type and therefore has a prototype property.

getTypeArg(Number);

Instances

The same is not so easy for instances.

function getInstance(inst: any): void {
    ...
}

Allows you to transfer any instance

getInstance(123);
getInstance("Hello World");

But it also allows us to pass types that we don’t want.

getInstance(String);

we can fix this with an alias like

type Instance = {
    constructor: Function;
}

function getInstance(inst: Instance): void {
    ...
}

But this does not work, so the question is why?

+4
source share
1 answer

: , "", "". "" , TypeScript , . "", .

, , , constructor, :

console.log(String.constructor === Function) // true

, null undefined Instance. , Instance " prototype", :

type Instance = {
  constructor: Function;
  prototype?: never;  // prototype can be missing or undefined, that it    
}

, :

getInstance(123); // okay
getInstance("Hello World"); // okay
getInstance(String); // error as desired
getInstance(null); // error as desired I hope
getInstance(undefined); // error as desired I hope

, ; .

+5

Source: https://habr.com/ru/post/1695814/


All Articles