4

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?

0

1 Answer 1

9

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite, you still can have properties initialized in a variable declared as None like this: interface None { [n: string]: never } ; function f(): never { throw new Error(); } ; const myVar: None = { q: f() }. But for all practical purposes never indexer is good enough.
@artem ok, yes if you have something that returns never you can assign that into a property, but if it just returns never it will always be a runtime error anyway I think. I am thinking of a solution that covers this as well, I will update if I come up with anything :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.