Search code examples
typescripttsc

Shorthand for `any` on a TS interface


I accidentally got this and it seems to work:

export interface ITestBlockOpts {
  desc: string,
  title: string,
  opts: Object,
  suman: ISuman,
  gracefulExit,
  handleBeforesAndAfters, 
  notifyParent
}

for the lines:

 gracefulExit,
  handleBeforesAndAfters, 
  notifyParent

is that syntax short for

  gracefulExit: any
  handleBeforesAndAfters: any
  notifyParent: any

?


Solution

  • Yes. the TypeScript compiler has an option to assume untyped variables should be typed as any. This is the noImplicitAny option which is false by default.

    It exists primarily to allow for easier conversion from JavaScript (of which TypeScript is a strict superset-of, i.e. all valid JavaAscript is valid TypeScript when noImplicitAny == false).

    If you're using TypeScript in a greenfield or all-TypeScript project then you should work with noImplicitAny == true to ensure that you always use typed variables and fields.

    Note that in TypeScript, if an interface member has an any type (whether implicit or not) it is not the same thing as an optional (undefined) member.

    ...so these interfaces are equivalent:

    interface Foo {
        a: any           // explicit `any` type
    }
    interface Bar {
        a                // implicit 'any' type
    }
    

    ...but these interfaces are not equivalent:

    interface Foo {
        a: any
    }
    interface Baz {
        a?: any          // explicit `any` type, but `a` can also be `undefined`
    }
    interface Qux {
        a?               // implicit `any`, but `a` can also be `undefined`
    }