添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

I really like the power of interfaces in TypeScript and its duck typing. But what really bothers me is that I cannot check whether is something an instance of interface.

For example, we have decided to build a role model for the user class. User class will have different roles and based on role type it either has permissions or not. And we decided to describe roles as interfaces.

So I want to have code like this:

class User {
    constructor(readonly role: IReader | IWriter){};
interface IReader  {
interface IWriter {
    readonly permissions: Array<string>
function guardAccess(user: User){
    // Oh no it is not working 😱
    // Error TS2693
    if (user.role instanceof IReader){
      throw new AccessDeniedException();
function guardAccess(user: User){
    // ✔️ no error
    if (user.role.name === "reader"){
      throw new AccessDeniedException();
    Enter fullscreen mode
    Exit fullscreen mode
// lets create a user with role reader
const user = getUser();
if (user.role.name === "reader"){
    user.role.name;
    user.role.permissions; // 🛑 error
else if (user.role.name === 'writer'){
    user.role.name;
    user.role.permissions; // ✔️ no error
    Enter fullscreen mode
    Exit fullscreen mode
if (user.role.name === "editor"){
 // 🛑 Error: TS 2367This condition will always return 'false'
 // since the types '"reader" | "writer"' and '"editor"' 
 // have no overlap.
    Enter fullscreen mode
    Exit fullscreen mode

That is it. Now we can have similar behavior to the instance of the interface in TypeScript.

Thank you for reading!

function guardAccess(user: User) { if (!user.permissions.includes(Permission.canWrite)) { throw new AccessDeniedException(); Enter fullscreen mode Exit fullscreen mode

This article is not about specific domain but about how to check interface at runtime.

And proposed solution works if you don’t need polymorphism.
For example you have role reader that can only read and role writer with claims for what it can write.

Once unpublished, all posts by worldpwn will become hidden and only accessible to themselves. If worldpwn is not suspended, they can still re-publish their posts from their dashboard.