在Typescript对象中设置元素的值

时间:2017-01-17 13:52:32

标签: typescript

我在TS中定义了一个对象:

public static string connectionString = ...; // get your connection string from encrypted config

// assumes your FILESTREAM data column is called Img in a table called ImageTable
const string sql = @"
    SELECT            
        Img.PathName(),
        GET_FILESTREAM_TRANSACTION_CONTEXT()
      FROM ImageTagble
      WHERE ImageId = @id";

public string RetreiveImage(int id)
{
    string serverPath;
    byte[] txnToken;
    string base64ImageData = null;
    using (var ts = new TransactionScope())
    {
        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    rdr.Read();
                    serverPath = rdr.GetSqlString(0).Value;
                    txnToken = rdr.GetSqlBinary(1).Value;
                }
            }
            using (var sfs = new SqlFileStream(serverPath, txnToken, FileAccess.Read))
            {
            // sfs will now work basically like a FileStream.  You can either copy it locally or return it as a base64 encoded string
               using (var ms = new MemoryStream())
               {
                  sfs.CopyTo(ms);
                  base64ImageData = Convert.ToBase64String(ms.ToArray());
               }
            }
        }
        ts.Complete();
        // assume this is PNG image data, replace PNG with JPG etc. as appropraite.  Might store in table if it will vary...
        return "data:img/png;base64," + base64ImageData;
    }
}

我想设置section1的值。我怎样才能做到这一点?我在尝试:

reportObj : {
  'report' : {
    'pk' : '',
    'uploaded' : '',
    'sections' : {
      'section1' : '',
      'section2' : '',
      'section3' : ''
    }
  }
};

此操作失败,我收到错误:

  

未捕获(承诺):TypeError:无法读取未定义

的属性“report”

我做错了什么?

1 个答案:

答案 0 :(得分:1)

该类型的定义应为:

reportObj: {
  'report': {
    'pk': string,
    'uploaded': string,
    'sections': {
      'section1': string,
      'section2': string,
      'section3': string
    }
  }
};

修改

定义变量/成员类型不会为其赋值 这样:

let reportObj: {
    report: {
        pk: string,
        uploaded: string,
        sections: {
            section1: string,
            section2: string,
            section3: string
        }
    }
};

console.log(reportObj.report);

在运行时会失败,因为变量reportObj只有一个类型,而不是一个值 要分配值:

type Reporter = {
    report: {
        pk: string,
        uploaded: string,
        sections: {
            section1: string,
            section2: string,
            section3: string
        }
    }
};

let reportObj = {} as Reporter;

console.log(reportObj.report); // undefined

但是这仍然会引发运行时错误:

console.log(reportObj.report.pk);

这将分配正确的值:

let reportObj = {
    report: {
        sections: {}
    }
} as Reporter;