Angular2 中使用 TypeScript 的嵌套函数



我正在从 Angular 1 迁移到 2,我在 JavaScript 中有嵌套函数:

function normalizeDoc(doc, id) {
    function normalize(doc){...

删除了"函数",但现在我从 TypeScript 收到错误。

import { Injectable } from '@angular/core';

@Injectable()
export class PouchSeed {
    constructor(
    ) {
    }
    normalizeDoc(doc, id) {
        normalize(doc) {
            doc = angular.copy(doc);
            Object.keys(doc).forEach(function (prop) {
                var type = typeof doc[prop];
                if (type === 'object') {
                    doc[prop] = normalize(doc[prop]);
                } else if (type === 'function') {
                    doc[prop] = doc[prop].toString();
                }
            });
            return doc;
        };
        var output = normalize(doc);
        output._id = id || doc._id;
        output._rev = doc._rev;
        return output;
    };

错误:

Typescript Error
';' expected.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {
        doc = angular.copy(doc);
Typescript Error
Cannot find name 'normalize'.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {
Typescript Error
Cannot find name 'angular'.
src/providers/pouch-seed.ts
normalize(doc) {
    doc = angular.copy(doc);

像这样嵌套方法可以吗?";"错误的原因是什么?

如果将es2016es2017库添加到编译器中,请在 tsconfig.json 中:

  "compilerOptions": {
    "lib": [
      ..., "es2016", "es2017"
    ]
  }

您可以使用对象展开、Object.entries和 TypeScript 解构:

export class PouchSeed {
  constructor() { }
  normalizeDoc(doc, id) {
    const normalize = o =>
      Object.entries(o)
        .map(([key, value]) => ({
          [key]: typeof value === 'object' ? normalize(value) ? typeof value === 'function' : value.toString() : value
        }))
        .reduce((acc, value) => ({ ...acc, ...value }), {});
    return { ...normalize(doc), _id: id || doc._id, _rev: doc._rev };
  };
}

相关内容

  • 没有找到相关文章

最新更新