Skip to content

Commit

Permalink
Add TypeScript definition (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
BendingBender authored and sindresorhus committed Apr 30, 2019
1 parent f2448e1 commit 018e116
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 9 deletions.
28 changes: 28 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
Simple micro templating.
@param template - Text with placeholders for `data` properties.
@param data - Data to interpolate into `template`.
@example
```
import pupa = require('pupa');
pupa('The mobile number of {name} is {phone.mobile}', {
name: 'Sindre',
phone: {
mobile: '609 24 363'
}
});
//=> 'The mobile number of Sindre is 609 24 363'
pupa('I like {0} and {1}', ['🦄', '🐮']);
//=> 'I like 🦄 and 🐮'
```
*/
declare function pupa(
template: string,
data: unknown[] | {[key: string]: unknown}
): string;

export = pupa;
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ module.exports = (template, data) => {
const regex = /{(.*?)}/g;

return template.replace(regex, (_, key) => {
let ret = data;
let result = data;

for (const prop of key.split('.')) {
ret = ret ? ret[prop] : '';
for (const property of key.split('.')) {
result = result ? result[property] : '';
}

return ret || '';
return result || '';
});
};
12 changes: 12 additions & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {expectType} from 'tsd';
import pupa = require('.');

expectType<string>(
pupa('The mobile number of {name} is {phone.mobile}', {
name: 'Sindre',
phone: {
mobile: '609 24 363'
}
})
);
expectType<string>(pupa('I like {0} and {1}', ['🦄', '🐮']));
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
"node": ">=6"
},
"scripts": {
"test": "xo && ava"
"test": "xo && ava && tsd"
},
"files": [
"index.js"
"index.js",
"index.d.ts"
],
"keywords": [
"string",
Expand All @@ -40,7 +41,8 @@
"micro"
],
"devDependencies": {
"ava": "^0.25.0",
"xo": "^0.23.0"
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Text with placeholders for `data` properties.

#### data

Type: `Object` `Array`
Type: `object | unknown[]`

Data to interpolate into `template`.

Expand Down

0 comments on commit 018e116

Please sign in to comment.