#Classes duck typing

9 messages · Page 1 of 1 (latest)

fervent radish
#

Hello, I am annoyed lately by TypeScript duck typing working on classes! An example:

export class PermissionActionDto {
  name: string;
  mode: ActionMode;

  @Expose({ groups: ["admin"] })
  createdAt?: Date;

  toString() { return "XD" }
}

// The following line is completely valid for typescript
const act: PermissionActionDto = { name: "List", mode: ActionMode.Allow }

It's perfectly valid for TSC, but decorator Expose won't work on it cause it's not an instance of a class. What's more instanceof won't work either. But there's more! If you define custom toString method, guess what? Yeah, plain object will be valid too, cause every object has toString method.

Is there any ESLint plugin or something that would warn me if I try to assign plain object to class type or another class instance that's not a child of specified type?

timid mulch
#

Why won't instanceof work?

fervent radish
timid mulch
fervent radish
#

Yeah but what I meant is that we have type of our variable PermissionActionDto which is class, so we could assume that this variable is instance of this class, but in this case it's not. It's little unexpected when instanceof returns false here, I would rather expect that TSC would return type error at compilation time. It feels a little bit like typescript lying about type, coz we don't know for sure if it's instance of class or just plain js object with matching structure.

#

So I am searching for some easy solution that would prevent those lies from code, via ES Lint rule or something...

timid mulch
#

Ah I see. That's an "issue" with the way typescript was designed to work, so that it would be easily interoperable with JavaScript, easy buy in and all that.

fervent radish
#

Yeah, but it would be nice to have opt-in more strictness

timid mulch
#

It'd be nice, sure, but I don't think the Typescript team plans on adding that in