born2net
born2net

Reputation: 24993

Can you explain this Typescript snippet?

Can you explain this Typescript snippet?

interface Validator<T extends Control> {
    (c:T): {[error: string]:any};
 }

So it's an interface extending Control, which has a function (method) that accepts the same type of class (generic) as passed into Validator (T), and that method returns a type of an object of ...??? now that part I am confused on:

 {[error: string]:any};

It's a type of object? any? not sure?!

tx

Sean

Upvotes: 1

Views: 86

Answers (2)

JKillian
JKillian

Reputation: 18351

Validator is an interface with one type parameter, T. T extends Control, so whatever is supplied as T must extend Control. (See the language spec for more on this.)

Objects that implement the Validator interface are callable (they are a function). When called, Validator objects expect one argument of type T and return an object. This object can be indexed into with strings which could map to a value of any type. The [error: string]:any notation is called an index signature and is explained in prose here. It essentially just means you can access an object with brackets instead of dot-notation.

Thus an example usage might look something like:

const someValidator = getValidatorOfTypeT();
someValidator(objectOfTypeT)["stringKey"] // is of type `any`

Upvotes: 2

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221412

{
  [error: string]:any;
}

This is called an index signature. It says that when the object is indexed by a string, e.g. foo["something"], the result is of type any, and that all declared properties of the type are assignable to any (though this doesn't mean anything in particular since everything is assignable to any).

Upvotes: 2

Related Questions