Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intentionally define an "empty interface" in typescript

TypeScript allows checking for checking unknown properties. The following

interface MyInterface {
  key: string
}

const myVar: MyInterface = {
  asda: 'asdfadf'
}

will fails with

Type '{ asda: string; }' is not assignable to type 'MyInterface'.
Object literal may only specify known properties, and 'asda' does not exist in type 'MyInterface'.

However, this statement will compile without any issue. Empty interface will accept any value

interface EmptyInterface {
}

const myVar: EmptyInterface = {
  asda: 'asdfadf'
}

However, what if I actually want to define type for an empty object that may not have any properties? How can I accomplish that in typescript?

like image 791
Tony Avatar asked Oct 18 '25 17:10

Tony


1 Answers

To define an interface that never has any members, you can define an indexer that returns never

interface None { [n: string]: never } 
// OK
let d2 : None = {

}
let d3 : None = {
    x: "" // error
}
like image 167
Titian Cernicova-Dragomir Avatar answered Oct 21 '25 08:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!