mgs*_*mgs 215 dictionary initialization typescript
给出以下代码
interface IPerson {
firstName: string;
lastName: string;
}
var persons: { [id: string]: IPerson; } = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
Run Code Online (Sandbox Code Playgroud)
为什么不初始化被拒绝?毕竟,第二个对象没有"lastName"属性.
tho*_*aux 247
编辑:此后已在最新的TS版本中修复.引用@ Simon_Weaver对OP帖子的评论:
注意:此后已经修复(不确定哪个TS版本).我在VS中遇到这些错误,正如您所期望的那样:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
您可以通过在声明和初始化中拆分示例来使用类型化字典,例如:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
Run Code Online (Sandbox Code Playgroud)
dmc*_*mck 58
我同意thomaux初始化类型检查错误是TypeScript错误.但是,我仍然希望找到一种方法,在单个语句中使用正确的类型检查来声明和初始化Dictionary.此实现更长,但它添加了其他功能,如a containsKey(key: string)和remove(key: string)方法.我怀疑,一旦0.9版本中提供了泛型,这可以简化.
首先,我们声明基本的Dictionary类和接口.索引器需要该接口,因为类无法实现它们.
interface IDictionary {
add(key: string, value: any): void;
remove(key: string): void;
containsKey(key: string): bool;
keys(): string[];
values(): any[];
}
class Dictionary {
_keys: string[] = new string[];
_values: any[] = new any[];
constructor(init: { key: string; value: any; }[]) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
add(key: string, value: any) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): any[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary {
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们声明Person特定类型和Dictionary/Dictionary接口.在PersonDictionary中注意我们如何覆盖values()和toLookup()返回正确的类型.
interface IPerson {
firstName: string;
lastName: string;
}
interface IPersonDictionary extends IDictionary {
[index: string]: IPerson;
values(): IPerson[];
}
class PersonDictionary extends Dictionary {
constructor(init: { key: string; value: IPerson; }[]) {
super(init);
}
values(): IPerson[]{
return this._values;
}
toLookup(): IPersonDictionary {
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的初始化和使用示例:
var persons = new PersonDictionary([
{ key: "p1", value: { firstName: "F1", lastName: "L2" } },
{ key: "p2", value: { firstName: "F2", lastName: "L2" } },
{ key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();
alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2
persons.remove("p2");
if (!persons.containsKey("p2")) {
alert("Key no longer exists");
// alert: Key no longer exists
}
alert(persons.keys().join(", "));
// alert: p1, p3
Run Code Online (Sandbox Code Playgroud)
Amo*_*hor 57
要在typescript中使用字典对象,您可以使用如下界面:
interface Dictionary<T> {
[Key: string]: T;
}
Run Code Online (Sandbox Code Playgroud)
并将其用于您的类属性类型.
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
Run Code Online (Sandbox Code Playgroud)
使用和初始化这个类,
getUsers(): Observable<any> {
var searchParams = new SearchParameters();
searchParams.SearchFor['userId'] = '1';
searchParams.SearchFor['userName'] = 'xyz';
return this.http.post(searchParams, 'users/search')
.map(res => {
return res;
})
.catch(this.handleError.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
aWe*_*per 15
Typescript 在您的情况下失败,因为它期望所有字段都存在。使用Record 和 Partial实用程序类型来解决它。
Record<string, Partial<IPerson>>
interface IPerson {
firstName: string;
lastName: string;
}
var persons: Record<string, Partial<IPerson>> = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
Run Code Online (Sandbox Code Playgroud)
解释。
备用。
如果您希望姓氏可选,您可以附加一个 ? Typescript 会知道它是可选的。
lastName?: string;
Run Code Online (Sandbox Code Playgroud)
https://www.typescriptlang.org/docs/handbook/utility-types.html
vik*_*ian 12
Record<Tkey, Tobject> 有点像 C# 字典
\nlet myRecord: Record<string, number> = {}; \n\n//Add\nmyRecord[\xe2\x80\x9dkey1\xe2\x80\x9d] = 1;\n\n//Remove\ndelete myRecord[\xe2\x80\x9dkey1"];\n\n//Loop\nfor (var key in myRecord) {\n var value = myRecord[key];\n}\nRun Code Online (Sandbox Code Playgroud)\n
这是一个更通用的字典实现,灵感来自@dmck
interface IDictionary<T> {
add(key: string, value: T): void;
remove(key: string): void;
containsKey(key: string): boolean;
keys(): string[];
values(): T[];
}
class Dictionary<T> implements IDictionary<T> {
_keys: string[] = [];
_values: T[] = [];
constructor(init?: { key: string; value: T; }[]) {
if (init) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
}
add(key: string, value: T) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): T[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary<T> {
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您正在寻找一种即使在打字稿中也能创建字典的简单方法,那就是使用 Map 对象。文档链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map。Map对象有添加、检索、删除和移除所有元素的主要方法。
dictionary= new Map<string, string>();
dictionary.set("key", "value");
dictionary.get("key");
dictionary.delete("key");
dictionary.clear(); //Removes all key-value pairs
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您想忽略某个属性,请通过添加问号将其标记为可选:
interface IPerson {
firstName: string;
lastName?: string;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
324160 次 |
| 最近记录: |