Oct 7, 2020

Demystify typescript keyword type and typeof

In typescript, keyword 'type' is used to alias existing types or anonymous types. This is typescript feature, and it has nothing to do with JavaScript. While const/let are used to declare variable in JavaScript.

class Person {
   constructor(public name: string) {}

type PersonAlias = Person; // Person is used as a type
const Person2 = Person;    // Person is used as a value

type PersonAlias2 = Person2; // error, Person2 is a value, not a type
type PersonAlias3 = PersonAlias; // ok, PersonAlias is a type

Because you can not assign value to a type, typescript introduced a keyword 'typeof', which can convert a value into a type. But don't be confused with JavaScript keyword 'typeof', which convert a value into a string value, such as "function", "string", etc.

const p = new Person('john');
type PersonAlias4 = typeof p; // typescript type
const typeName = typeof p; // javascript vlaue: "object"

In the following code, the Person class can be used as a typescript type and a javascript vlaue. If it is used as value, it is a bit confusing.

type PersonClass = typeof Person; // Person is used as javascript vlaue
type PersonAliase4 = Person;  // Person is used as a typescript type

let personInstance: PersonAliase4 = new Person('john'); // ok

let personClass: PersonClass = personInstance; // error; type of "Person" 
// is not the type of "typeof Person" :)

personClass = class { constructor(public name: string) { } }; //ok

You can test the code here

No comments:

Post a Comment