From 34b2133e83cab6ea4b16e49b8c50b1f02867df7d Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Thu, 7 Sep 2017 00:41:24 +0900 Subject: [PATCH] Exploit generics to assert typings of custom data --- types/vfile/index.d.ts | 15 ++++++++++----- types/vfile/vfile-tests.ts | 13 ++++++++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index 661669c813..cd22972964 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -24,7 +24,8 @@ declare namespace vfile { position?: Position; } - interface VFileParams { + interface VFileParamsBase { + data?: D; contents?: Contents; path?: string; basename?: string; @@ -34,6 +35,8 @@ declare namespace vfile { cwd?: string; } + type VFileParams = VFileParamsBase & C; + interface VFileError { ruleId: string | null; name: string; @@ -56,13 +59,13 @@ declare namespace vfile { type ToString = (encoding?: BufferEncoding) => string; - interface VFile { - (input?: Contents | VFile | VFileParams): VFile; + interface VFileBase { + (input?: Contents | VFile | VFileParams): VFile; message: Message; fail: Fail; info: Info; history: string[]; - data: {}; + data: D; messages: VFileError[]; contents: Contents; path?: string; @@ -73,8 +76,10 @@ declare namespace vfile { cwd: string; toString: ToString; } + + type VFile = VFileBase & C; } -declare const vfile: vfile.VFile; +declare const vfile: vfile.VFile<{}, {}>; export = vfile; diff --git a/types/vfile/vfile-tests.ts b/types/vfile/vfile-tests.ts index e5a11f2185..f81a15a24c 100644 --- a/types/vfile/vfile-tests.ts +++ b/types/vfile/vfile-tests.ts @@ -1,6 +1,13 @@ import vfile = require("vfile"); -const file = vfile({path: '~/example.txt', contents: 'Alpha *braavo* charlie.'}); +const file = vfile({ + path: '~/example.txt', + contents: 'Alpha *braavo* charlie.', + custom: 'Custom tango', + data: { + custom: 12345 + } +}); file.path; // => '~/example.txt' file.dirname; // => '~' @@ -16,3 +23,7 @@ file.history; // => ['~/example.txt', '~/example.md', '~/index.text'] file.message('`braavo` is misspelt; did you mean `bravo`?', {line: 1, column: 8}); console.log(file.messages); + +// Keep typings of custom data +const custom: string = file.custom; // 'Custom tango' +const dataCustom: number = file.data.custom; // 12345