Exploit generics to assert typings of custom data

This commit is contained in:
Junyoung Choi
2017-09-07 00:41:24 +09:00
parent 61cf931b24
commit 34b2133e83
2 changed files with 22 additions and 6 deletions
+10 -5
View File
@@ -24,7 +24,8 @@ declare namespace vfile {
position?: Position;
}
interface VFileParams {
interface VFileParamsBase<D> {
data?: D;
contents?: Contents;
path?: string;
basename?: string;
@@ -34,6 +35,8 @@ declare namespace vfile {
cwd?: string;
}
type VFileParams<C, D> = VFileParamsBase<D> & 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<C, D> {
<C>(input?: Contents | VFile<C, D> | VFileParams<C, D>): VFile<C, D>;
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<C, D> = VFileBase<C, D> & C;
}
declare const vfile: vfile.VFile;
declare const vfile: vfile.VFile<{}, {}>;
export = vfile;
+12 -1
View File
@@ -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