typescript-eslint: [ban-types] Should not ban `{}` by default!

A lot of type declaration is using Type Aliases, to let user fill in.

For example a interface like this: (I got it from an official repo)

  interface Custom<
    Detail = Record<string, any>,
    TargetDataset = Record<string, any>,
    CurrentTargetDataset = Record<string, any>,
    Mark = Record<string, any>
  > extends Base<TargetDataset, CurrentTargetDataset, Mark> {
    detail: Detail;
  }

Sometimes detail is just an empty object! So it’s good for me to write Custom<{}>, but V3 will throw an error ( not even a warning)

Don't use `{}` as a type. `{}` actually means "any non-nullish value".
- If you want a type meaning "any object", you probably want `Record<string, unknown>` instead.
- If you want a type meaning "any value", you probably want `unknown` instead.

In order to stop this error, I have to write Custom<Record<never,never>>, which is unneeded and a waste of time.

So stop baning {} by default. May packages are holding certain objects for certain data, and to prevent the Cannot read property 'xxx' of undefined, they are usually initialize with {}, so If I know that those fields are not containing any data, I should use {}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 25 (18 by maintainers)

Most upvoted comments

Just been hit by this, in my case with React empty Props:

type Props = {};

const Button: FunctionComponent<Props> = () => {
  // ...
}

Is a pretty common pattern especially when you rely on user snippets to speed up development.

I understand that the typing is wrong, but IMO it is a typescript quirk ({} should be the type of an empty object) and enforcing this eslint rule will lead to a loss of both productivity (ability to quickly add props to an empty object from a generated user snippet) and readability (where are my props, what is this crazy Omit<Record<string, never>, keyof string> type?).

What’s frustrating is that it looks like we can’t really disable this only ban-type without having to inline the whole rule config, messy! Guess I should open a separate issue about that.


Maintainer Edit

See workaround in the above comment

I ran into exactly what @zetoke mentioned above: empty props, but non-empty state. I thought the solution you mention here would work, @bbarry, but playing with it in the TS playground (3.9.2), I noticed it will actually let you reference any properties in the function body (these are typed never, so there’s little potential for misuse, but apparently I can still pass use those as, e.g., arguments to functions like console.log that take any arguments).

Here are the different things I tried:

// the violation at the heart of the discussion
type Props1 = {}

const c2 = (p: Props1) => {
    console.log(p.doesNotExist) // TS complains 👍
}

c2(42) // TS does not complain 😮
c2({})

// proposed above
type Props2 = Omit<Record<string, never>, keyof string>

const c1 = (p: Props2) => {
    console.log(p.doesNotExist) // TS does not complain 😮
}

c1(42) // TS complains 👍
c1({})

// using unknown
type Props3 = unknown

const c3 = (p: Props3) => {
    console.log(p.doesNotExist) // TS complains 👍
}

c3(42) // TS does not complain 😮
c3({})

(I’m using a simple function instead of a React component because it’s simpler, but I think this translates to the class-based component discussion pretty easily). I think there are two things we want to ensure when declaring a type on a function: that callers are prevented from passing in bogus values, and that the specified type represents the value within the function body to avoid implementation mistakes. I think the interesting thing here is that you’re almost never calling a React component function (or creating a React component class instance) directly, so the first part is largely moot (in the no-props case). This is more about saying “I don’t want the type of the props object to have any properties I (or a future maintainer) might accidentally reference in the component implementation”. Given that, I think unknown is probably more useful for React (even though it has the same exact issue the rule appears to be warning against).

It’d be nice to have more explicit guidance in the hint for the React case, though. Right now, it says

  6:3  error  Don't use `{}` as a type. `{}` actually means "any non-nullish value".
- If you want a type meaning "any object", you probably want `Record<string, unknown>` instead.
- If you want a type meaning "any value", you probably want `unknown` instead  @typescript-eslint/ban-types

I don’t really want either of these: I want a type meaning “an object with no properties”. Do you think it’s reasonable to expand this text to include a hint for that case?

I’m still very confused about what {} means, and it seems like almost everybody use it as an object. It’s also used extensively in the typings of react.

It’s working perfectly well for typing React components without props:

const Comp = (props: {}) => null; // React component

const a = <Comp /> // Correct

const b = <Comp test={false} /> // Type '{ test: boolean; }' is not assignable to type '{}'. Property 'test' does not exist on type '{}'.(2322)

What alternative should I use to replace {} in this case?

It would be great if a suggestion could be added to the rule for what to use when you use {} as meaning “empty object”. Most uses that I have are where the type is & with some other type, and I just want it to not change the other type.

unknown does work for this, but it’s not intuitive at all. Record<string, never> also works. Omit<Record<string, never>, keyof string> works and is more strict. One of these should be added as a third suggestion of how to fix the lint.

It isn’t banning the value {}

It is banning the type.

As the error states

 `{}` actually means "any non-nullish value".

That means for your interface if it had {} as a type would permit almost any value in that position:

Yes, that’s it! There is and should be an

an empty object

at that position!

As to it being common… doesn’t mean it is correct.

Please check out carefully what others wants to say before talking something big to them ok?

@bbarry

@bbarry Thanks for the explanation. It makes sense to me. I feel TypeScript should clarify and provide a helper type for empty object because it’s used a lot.

It isn’t that bad of a problem for React because your call to React.createComponent is passing the parameter to an intersection type resulting in the actual parameter being the intersection React.Attributes & {}. Unfortunately there is no way for ts-eslint to know that is a React component and the type of the parameter is actually going to be an intersection with some other interface when it actually gets used.

I would consider:

const Comp = (props: React.Attributes) => null; 

The thing is that you can call that function just like any ordinary function:

const result = Comp({});

With the type specified as {} the following code is valid:

const result = Comp(4);

which is surely not what you intend.

unknown does work indeed, thanks. It’s not very intuitive, I wish TS would address {} somehow.

Can’t you use unknown for that?

interface IState {
  field: string;
}

class MyComponent extends React.Component<unknown, IState> {
  public foo() {
    // @ts-expect-error Property 'kek' does not exist on type 'Readonly<unknown> & Readonly<{ children?: ReactNode; }>'.(2339)
    const a = this.props.kek;
    console.log(a);
  }
}

If you intend on adding props later and want to track all of these unknowns with a named unknown type like type MyProps = unknown;

If you really wanted you could declare MyProps like this:

const __id = Symbol();
export class MyProps {
  [__id]: Symbol;

  constructor() { this[__id] = __id; }
};

export function isMyProps(input: unknown): input is MyProps {
    return (input as MyProps)?.[__id] === __id;
}

@bbarry what’s about

interface IState {
  field: string;
}

class MyComponent extends React.Component<{}, IState> {
...
}

the default value for props and state is {} in React components. And it makes sense since I can catch something like this:

public render() {
  const a = this.props.kek;
  console.log(a);
}

Property 'kek' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.ts(2339)

And this error is just muted with Record<string, unknown>

I am pretty confident these are all valid definitions for empty object:


type NoElements<T> = { [P in keyof T]: never };
type EmptyObject1 = NoElements<Record<string, never>>;

type EmptyObject2 = Omit<Record<string, never>, keyof string>;

type EmptyObject3 = Omit<Record<any, never>, keyof any>;

both Omit and never are very powerful language constructs for blacklisting things.

https://www.typescriptlang.org/play/index.html?target=7&ssl=7&ssc=57&pln=1&pc=1#code/FAFwngDgpgBAcgewKIBsoFsoDsQGcA8AKgHwwC8MA3jANoAKMAlljANZRgIBmMhAugC4YWKADcoAJxgBfANyhIsJOgjgA8gCMAVlADGIAIzl4yNJhwEASnoQSAJvlwgJzAOYAaYWMnFi8hdAwyqpgmjr6AEzGauiMIPjWurYOTi5YHl7iEsSe7Jw8qW5+wAFKKuraeiAAzNGx8YnJ+ACGWGCeIlk5bBzcMK1gxcBoIP1CwRXhNf7NxlgArigo8rMU81h2UFzMUHYrxgAM+xQGxzBc6-qMCCwAFACUVDJnYVUAdBASCCDfimciAHcYK99A8zgBycFnADKYHQGgQKDBwFWTwAHkIDs8SqjKHJgEA

Because the {} type does restrict what you can do with the type (it pretends to not know about any members that the type has for example). It just doesn’t restrict what values are instances of {} (except null or undefined).

interface AAA<T = Record<string,any>> {
  aaa: T;
}

const a: AAA = { aaa: { a: 1, b: 2 } };
const b: AAA<{ a?: number, b?: number }> = { aaa: { a: 1 } };
const c: AAA<{}> = { aaa: {} };
const d: AAA<Record<never, never>> = { aaa: {} };
type NoElements<T> = { [P in keyof T]: never };
type EmptyObject = NoElements<Record<string,never>>;
const e: AAA<EmptyObject> = { aaa: {} };

a.aaa.error = 1;
b.aaa.error = 1; // Property 'error' does not exist on type '{}'.(2339) 
c.aaa.error = 1; // Property 'error' does not exist on type '{}'.(2339) 
d.aaa.error = 1; // Property 'error' does not exist on type 'Record<never, never>'.(2339)
e.aaa.error = 1; // Type '1' is not assignable to type 'never'.(2322)

a.aaa = {};
b.aaa = {};
c.aaa = {};
d.aaa = {};
e.aaa = {};

a.aaa = { a: 1 };
b.aaa = { a: 1 };
c.aaa = { a: 1 };
d.aaa = { a: 1 };
e.aaa = { a: 1 }; // Type 'number' is not assignable to type 'never'.(2322)

a.aaa = { error: 1 };
b.aaa = { error: 1 }; // Type '{ error: number; }' is not assignable to type '{ a?: number | undefined; b?: number | undefined; }'.(2322)
c.aaa = { error: 1 };
d.aaa = { error: 1 };
e.aaa = { error: 1 }; // Type 'number' is not assignable to type 'never'.(2322)

a.aaa = 1; // Type '1' is not assignable to type 'Record<string, any>'.(2322)
b.aaa = 1; // Type '1' has no properties in common with type '{ a?: number | undefined; b?: number | undefined; }'.(2559)
c.aaa = 1;
d.aaa = 1;
e.aaa = 1; // Type '1' is not assignable to type 'NoElements<Record<string, never>>'.(2322)

No you are not clear because that code is not reasonable:

interface Sample<T = Record<string,any>> {
  aaa: {};
}

The generic type here is unused. The type definition is almost certainly not what you actually think you mean.

I’ll assume you meant:

interface AAA<T = Record<string,any>> {
  aaa: T;
}

which means that these are both fine:

const a: AAA = { aaa: { a: 1, b: 2} };
const a: AAA<{ a: number, b?:number}> = { aaa: { a: 1} };

This however:

const a:AAA<{}> = { aaa: {} };

does NOT mean “we just want that property to be an empty object.”

instead it means “that property can be almost anything”

This:

const a:AAA<Record<never, never>> = { aaa: {} };

also doesn’t mean “we just want that property to be an empty object.” Instead it means “we want an object and aren’t going to use any members that happen to be there.”

If you really mean “we just want that property to be an empty object” then you need some fancy types:

type NoElements<T> = { [P in keyof T]: never };
type EmptyObject = NoElements<Record<string,never>>;

const e: AAA<EmptyObject> = { aaa: {} };
// @ts-expect-error
e.aaa = { asdf: 1 };

Playground link