繁体   English   中英

如何从 Map 返回强类型值<string, object>方法

[英]How to return strongly typed value from a Map<string, object> method

我使用 C# 已经有一段时间了,最​​近开始使用 TypeScript V3.1.6 开发 Node.js 项目。 我很高兴 Typescript 现在支持泛型,这是我期望从 C# 过渡时失去的东西之一。

我的 C# 代码是一个 DataRow 包装器,允许我使用泛型从字典中提取强类型值,如下所示:

Dictionary<string, object> Values = new Dictionary<string, object>();
public T Parse<T>(string columnName)
{
    T result = default(T);
    result = (T)Convert.ChangeType(this.Values[columnName], typeof(T));
    return result;
}

我目前的 TypeScript 代码如下:

export class DataRow {
    private Values: Map<string, object> = new Map<string, object>();
    constructor(row?: any) {
        if (!!row) {
            for (let key in row) {
                this.Values.set(key, row[key]);
            }
        }
    }

    public Value<T>(key: string): T {
         //Not exactly how to replicate the return.
    }
}

我的 C# 代码中的行:

T result = default(T);

如果值为空,则允许我返回该类型的默认值。 为简洁起见,我从 C# 示例中删除了其他几个空检查和字典检查。 我的主要想法/问题是:

1) 你能在 Typescript 中获得泛型的默认类型吗?

2) 由于我是 TypeScript 的新手,请随时指出到目前为止我的 TypeScript 代码的任何明显问题。

3) 返回强类型值是否会影响 Node.js 的性能?

更新:

我已经将我的课程更新为:

export class DataRow {

    private Values = new Map<string, any>();

    constructor(row?: any) {
        if (!!row) {
            for (let key in row) {
                this.Values.set(key, row[key]);
            }
        }
    }

    public Value<T>(key: string): T {
        if (this.Values.has(key)) {
            let value = this.Values.get(key);

            if (!!value) {
                return value as T;
            }
        }
        return <unknown>null as T;
    }
}

现在效果很好。 谢谢您的帮助!

TypeScript 仅在构建时为您提供静态类型的好处。 在您的应用程序可以在 NodeJS 环境中执行之前,您的代码将被编译为 JavaScript,因此您不必担心返回任何强类型的东西,也不必担心性能,因为在您的应用程序中根本没有 TS运行。

至于您关于默认值的问题,您可以简单地检查该值是否存在于地图中,如果没有任何内容,则返回默认值。

public Value<T>(key: string): T {
  if (this.Values.has(key) {
    return this.Values.get(key)
  } else {
    // return some kind of default.
  }
}

关于可能的改进,我建议您将您的类设为泛型以提高类型安全性。

// Class is now a generic with a default type of `object`.
export class DataRow<T = object> {
    // You don't need to explicitly type the Values. TS can infer that.
    private Values = new Map<string, T>();

    // Explicitly type the row argument for type safety.
    constructor(row?: { [key: string]: T }) {
        // In JS/TS land you don't have to explicitly cast
        // values to booleans to be able to make a truth check.
        if (row) {
            for (let key in row) {
                this.Values.set(key, row[key]);
            }
        }
    }

    public Value(key: string): T {
        if (this.Values.has(key)) {
             return this.Values.get(key)
        } else {
             // return some kind of a default
         }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM