0

I am trying to create a function fun that takes a wrapped designated object. I've wrapped it in Example.

export class Example {
  private __ExampleFlag;
  constructor (input) {
    Object.assign(this, input);
  }
}

Here's the function:

const fun = (e: Example): boolean => {
  return true;
};

This does not work, which is good:

fun({}); // no good

This works, which is good:

fun(new Example({})); // good

This works, which NOT is good:

const v:any = {};
fun(v); // not good

How can I have any not match Example? Haveing a more strict type?

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • what's the purpose of the `constructor` here? – molamk Feb 07 '19 at 16:52
  • 1
    `any` is by definition assignable to anything. Avoid `any` like the plague (you can usually avoid it). Use `unknown` if you don't know the type https://stackoverflow.com/questions/51439843/typescript-3-0-unknown-vs-any/51439876#51439876 – Titian Cernicova-Dragomir Feb 07 '19 at 16:55
  • @TitianCernicova-Dragomir but I am not allowing `any` as the argument to `fun` it's a class. Why isn't it limiting the argument to be an instance of `new Example`? – ThomasReggi Feb 07 '19 at 17:14
  • `any` includes the class `Example`. It means any type. Is this just for experimentation or for building something? There are legitimate cases where variables can be `any`, e.g parsing input from a http response. – shusson Feb 07 '19 at 17:16
  • `any` is special. It is at the same time assignable from any type and assignable to any type, and you can do anything with it without TS complaining about it. Basically anything that is `any` forgoes all type checking. This is why it is so dangerous – Titian Cernicova-Dragomir Feb 07 '19 at 17:19
  • You can also think of `any` as "turn off the type checker for this value and things it touches". `unknown` is the type-safe representation for "value I don't know the type of yet". – Jacob Gillespie Feb 08 '19 at 08:40

0 Answers0