简体   繁体   English

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

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

I have been working in C# for quite some time and have recently begun work on a Node.js project using TypeScript V3.1.6.我使用 C# 已经有一段时间了,最​​近开始使用 TypeScript V3.1.6 开发 Node.js 项目。 I was quite trilled that Typescript now supports generics which is one of the things I was anticipating loosing with the transition from C#.我很高兴 Typescript 现在支持泛型,这是我期望从 C# 过渡时失去的东西之一。

My C# code is a DataRow wrapper allowing me to extract strongly typed values from a Dictionary using generics and is as follows:我的 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;
}

My current TypeScript code is as follows:我目前的 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.
    }
}

The line in my C# code:我的 C# 代码中的行:

T result = default(T);

Allows me to return a default value for the type if the value is null.如果值为空,则允许我返回该类型的默认值。 I've removed several other null checks and dictionary checks from my C# example for brevity.为简洁起见,我从 C# 示例中删除了其他几个空检查和字典检查。 My primary thoughts/questions are:我的主要想法/问题是:

1) Can you get a default type of a generic in Typescript? 1) 你能在 Typescript 中获得泛型的默认类型吗?

2) Since I'm new to TypeScript, please feel free to point out any obvious issues with my TypeScript code thus far. 2) 由于我是 TypeScript 的新手,请随时指出到目前为止我的 TypeScript 代码的任何明显问题。

3) Will returning strongly typed values potentially influence performance in Node.js? 3) 返回强类型值是否会影响 Node.js 的性能?

UPDATE:更新:

I've updated my class to:我已经将我的课程更新为:

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;
    }
}

It works great now.现在效果很好。 Thanks for the help!谢谢您的帮助!

TypeScript gives you the benefits of static typing only at build time. TypeScript 仅在构建时为您提供静态类型的好处。 Your code will be compiled to JavaScript before your application can be executed in the NodeJS environment, so you don't have to worry about returning any strongly typed things, nor about the performance, as there will be no TS at all in your application at runtime.在您的应用程序可以在 NodeJS 环境中执行之前,您的代码将被编译为 JavaScript,因此您不必担心返回任何强类型的东西,也不必担心性能,因为在您的应用程序中根本没有 TS运行。

As for your question about the default value, you can simply check for the value's existence in the map and return a default if there's nothing there.至于您关于默认值的问题,您可以简单地检查该值是否存在于地图中,如果没有任何内容,则返回默认值。

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

Regarding the possible improvements, I would advise you to make your class into a generic to improve type safety.关于可能的改进,我建议您将您的类设为泛型以提高类型安全性。

// 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