Skip to content

Commit 61036c4

Browse files
committed
feat: required-options example
1 parent e1aebc5 commit 61036c4

File tree

5 files changed

+83
-0
lines changed

5 files changed

+83
-0
lines changed

examples/required-options/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# required options Example
2+
3+
`Base` has no required options by default, so the following code has no type errors.
4+
5+
```js
6+
import { Base } from "javascript-plugin-architecture-with-typescript-definitions";
7+
8+
const base1 = new Base();
9+
const base2 = new Base({});
10+
```
11+
12+
But required options can be added by extending the `Base.Optiions` interface.
13+
14+
```ts
15+
declare module "javascript-plugin-architecture-with-typescript-definitions" {
16+
namespace Base {
17+
interface Options {
18+
myRequiredUserOption: string;
19+
}
20+
}
21+
}
22+
```
23+
24+
With that extension, the same code will have type a type error
25+
26+
```ts
27+
// TS Error: Property 'myRequiredUserOption' is missing in type '{}' but required in type 'Options'
28+
const base = new Base({});
29+
```

examples/required-options/index.d.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Base } from "../../index.js";
2+
export { Base } from "../../index.js";
3+
4+
declare module "../.." {
5+
namespace Base {
6+
interface Options {
7+
myRequiredUserOption: string;
8+
}
9+
}
10+
}
11+
12+
export class MyBase extends Base {}

examples/required-options/index.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Base } from "../../index.js";
2+
3+
/**
4+
* @param {Base} base
5+
* @param {Base.Options} options
6+
*/
7+
function pluginRequiringOption(base, options) {
8+
if (!options.myRequiredUserOption) {
9+
throw new Error('Required option "myRequiredUserOption" missing');
10+
}
11+
}
12+
13+
export const MyBase = Base.plugin(pluginRequiringOption);
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { MyBase } from "./index.js";
2+
3+
// @ts-expect-error - An argument for 'options' was not provided
4+
new MyBase();
5+
6+
// @ts-expect-error - Type '{}' is missing the following properties from type 'Options': myRequiredUserOption
7+
new MyBase({});
8+
9+
new MyBase({
10+
myRequiredUserOption: "",
11+
});

examples/required-options/test.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { test } from "uvu";
2+
import * as assert from "uvu/assert";
3+
4+
import { MyBase } from "./index.js";
5+
6+
test("new MyBase()", () => {
7+
assert.throws(() => new MyBase());
8+
});
9+
10+
test("new MyBase({})", () => {
11+
assert.throws(() => new MyBase({}));
12+
});
13+
14+
test('new MyBase({ myRequiredUserOption: ""})', () => {
15+
assert.not.throws(() => new MyBase({ myRequiredUserOption: "" }));
16+
});
17+
18+
test.run();

0 commit comments

Comments
 (0)