Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

satisfies keyword for class declaration ? #60849

Open
6 tasks done
eczn opened this issue Dec 24, 2024 · 1 comment
Open
6 tasks done

satisfies keyword for class declaration ? #60849

eczn opened this issue Dec 24, 2024 · 1 comment

Comments

@eczn
Copy link

eczn commented Dec 24, 2024

πŸ” Search Terms

"satisfies with class", "satisfies for static", "class static typing", "static member typing", "type check for static mehods"

βœ… Viability Checklist

⭐ Suggestion

satisfies with class

interface FromJson {
  from(jsonString: string): ThisType<{}>;
}

class A { }
A satisfies FromJson; // βœ… works with type error:
                      // Property 'from' is missing in type 'typeof A' but required in type 'FromJson

class B {
  static from(jsonString: string) { return new B(); }
}
B satisfies FromJson; // βœ… works well, it ensures that the class B must to implement the `static from(...)`

const B = ( class { ... } ) satisfies FromJson; // workarounds in one line 

but ... all-in-one-lined satisfies doesn't works for class

tralling satisfies after class body

class C { } satisfies FromJson // ❌ it doesn't works with error: Unexpected keyword or identifier.(1434)

and put satisfies before class body could have a better taste

class D satisfies FromJson { } // ❌ it doesn't works with the same error

πŸ“ƒ Motivating Example

interface FromJson {
  from(type: string,json: string): ThisType<{}>
}

class A satisfies FromJson {
  from(type: string, json: string) {
    const obj = JSON.parse(json)
    if (obj.type === type) Object.assign(this, obj);
    throw new Error(`unexpected json`);
  }
}
class B satisfies FromJson { /* ... */ }
class C satisfies FromJson { /* ... */ }
class D satisfies FromJson { /* ... */ }

const typeMap = { A, B, C, D }
type ObjectTypes = keyof typeof typeMap;

const handleResponse(type: ObjectTypes, json: string): A | B | C | D {
  return typeMap[type].from(type, json)
}

πŸ’» Use Cases

What do you want to use this for?

for type-checking for static member of class in one line

What shortcomings exist with current approaches?

tralling satisfies after class body looks very bad for human eyes parsing

What workarounds are you using in the meantime?

// one line : 
const A = ( class { ... } ) satisfies FromJson;

// two line : 
class A { ... }
A satisfies FromJson;

expected :

class C implements I satisfies S {  }
@MartinJohns
Copy link
Contributor

Duplicate of #33892.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants