Skip to content
Advertisement

Type hints with user defined classes

Couldn’t seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass().

And then let’s say in some function, call it FuncA(arg), I have one argument named arg. Would the correct way to type hint FuncA be:

JavaScript

Or would it be:

JavaScript

Advertisement

Answer

The former is correct, if arg accepts an instance of CustomClass:

JavaScript

In case you want the class CustomClass itself (or a subtype), then you should write:

JavaScript

Like it is written in the documentation about Typing:

JavaScript

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C.

The documentation includes an example with the int class:

JavaScript
Advertisement