我使用的是最新的 Typescript 版本:2.6.2。
我遇到了一个奇怪的情况,如果我执行 foo({a:1,b:2}) - 事情不起作用,而如果我执行:foo({ b:2,a:1}) - 它们确实有效。
我有一个通用类,一个具有 2 个属性和一个函数的接口(interface)。
代码如下:
class MyClass<T> {
value: T;
next(value: T): void {
}
}
export enum StateKey { backlogItems='backlogItems'}
export interface State {
backlogItems : number[];
[key: string]: any
}
class A {
private subj = new MyClass<State>();
public set<T>(name: StateKey, state: T) {
this.subj.next({ backlogItems: [...this.subj.value.backlogItems] ,
[name]:state //<--- error here
})
}
}
我得到一个错误:
Argument of type '{ [name]: T; }' is not assignable to parameter of type 'State'. Types of property 'backlogItems' are incompatible. Type 'T' is not assignable to type 'number[]'.
但是如果我改变对象中文字的顺序:
来自:
this.subj.next({ backlogItems: [...this.subj.value.backlogItems], [name]: state })
到:
this.subj.next({ [name]:state, backlogItems: [...this.subj.value.backlogItems] })
问题
为什么改变顺序可以编译?
最佳答案
如果您将 StateKey 枚举中的字符串更改为其他值,它会编译而不会出错,如下所示
export enum StateKey { backlogItems='somethingElse'}
(如果您向枚举添加更多值,错误也会消失)
编译器正在做 type inference并检测到 next() 函数参数中的 [name] 只能是 backlogItems,声明为 number[] 。
所以对象字面量的两种变体都为同一个属性分配了两个不同的值,这就是分配顺序很重要的原因——基本上,最后一个获胜。如果最后分配的值与声明的属性类型不兼容,编译器会报告错误 - T 与 number[] 不兼容。
更新
此外,为了保留代码并消除错误,您可以让编译器忘记它为 name 推断的类型,方法是将它分配给带有 string<> 类型:
class MyClass<T> {
value: T;
next(value: T): void {
}
}
export enum StateKey { backlogItems='backlogItems'}
export interface State {
backlogItems : number[];
[key: string]: any
}
class A {
private subj = new MyClass<State>();
public set<T>(name: StateKey, state: T) {
const key: string = name;
this.subj.next({ backlogItems: [...this.subj.value.backlogItems] ,
[key]:state
})
}
}
关于javascript - typescript 介意对象文字中实例化的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48034555/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调