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

Add object handling for typescript/es6-declarations #718

Merged
merged 8 commits into from
Oct 28, 2021
47 changes: 31 additions & 16 deletions lib/common/formatHelpers/getTypeScriptType.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
/**
* Given some value, returns a basic valid TypeScript type for that value.
* Supports numbers, strings, booleans, and arrays of any of those types.
RobbyUitbeijerse marked this conversation as resolved.
Show resolved Hide resolved
*
*
* @memberof module:formatHelpers
* @example
* ```javascript
Expand All @@ -29,25 +29,40 @@
* }).join('\n');
* }
* });
*
*
* @param {*} value A value to check the type of.
* @return {String} A valid name for a TypeScript type.
* ```
*/
function getTypeScriptType(value) {
if (Array.isArray(value)) {
if (value.length > 0) {
const firstValueType = getTypeScriptType(value[0]);
if (value.every((v) => getTypeScriptType(v) === firstValueType)) {
return firstValueType + '[]';
}

function getTypeScriptType(passedValue) {
function getArrayType(passedArray) {
if (passedArray.length > 0) {
const firstValueType = getTypeScriptType(passedArray[0]);
if (passedArray.every((v) => getTypeScriptType(v) === firstValueType)) {
return firstValueType + '[]';
}
return 'any[]';
}

const type = typeof value;
if (['string', 'number', 'boolean'].includes(type)) return type;
return 'any';
return 'any[]';
}
RobbyUitbeijerse marked this conversation as resolved.
Show resolved Hide resolved

function getDataType(value) {
if (Array.isArray(value)) return getArrayType(value)
if (typeof value === 'object') return getObjectType(value)
if (['string', 'number', 'boolean'].includes(typeof value)) return typeof value

return 'any'
RobbyUitbeijerse marked this conversation as resolved.
Show resolved Hide resolved
}

const getObjectType = (passedObject) => {
return `{
${Object.entries(passedObject).map(([key, value]) => {
return `${key}: ${getDataType(value)},`
}).join('\n')}
}`
}
RobbyUitbeijerse marked this conversation as resolved.
Show resolved Hide resolved

module.exports = getTypeScriptType;

return getDataType(passedValue)
}

module.exports = getTypeScriptType;