Home > OS >  TS: convert `DateConstructor => Date` and `typeof MyClass => MyClass`
TS: convert `DateConstructor => Date` and `typeof MyClass => MyClass`

Time:01-27

How to convert DateConstructor type to Date?
And how to convert typeof MyClass to MyClass?

The code:   playground link

class MyDate extends Date { toNiceString () { return super.toString() } }
const skipObjectTypes = [Date, RegExp, MyDate] // for use as JS

/* problem here */
type SkipTypes = typeof skipObjectTypes[number]
// SkipTypes = typeof MyDate | DateConstructor | RegExpConstructor

/* desirable behavior */
type SkipTypesDesirable = Date | RegExp | MyDate

CodePudding user response:

[Date, RegExp, MyDate] will contain an array of classes, so typeof skipObjectTypes[number] will give you a union of those classes.

If you want the instance type, you can use the InstanceType conditional type:

class MyDate extends Date { toNiceString () { return super.toString() } }
const skipObjectTypes = [Date, RegExp, MyDate] // for use as JS

/* problem here */
type SkipTypes = InstanceType<typeof skipObjectTypes[number]>
// SkipTypes = typeof MyDate | DateConstructor | RegExpConstructor

Playground Link

CodePudding user response:

Found two ways to solve this:   playground link

type SkipTypesMethod1 = InstanceType<typeof skipObjectTypes[number]>
type SkipTypesMethod2 = typeof skipObjectTypes[number]["prototype"]

Thanks to @Titian Cernicova-Dragomir for the first way.

  •  Tags:  
  • Related