想为https://github.com/paldepind/union-type
撰写d.ts文件寻求帮助使用下面的联合类型
let Maybe = Type({
Nothing: []
, Just: [Number]
})
如果Maybe.Nothing()
输入错误为Maybe.None()
我尝试从对象文字中捕获键,但编译器仍然无法识别结果类型Nothing
中的Just
和Maybe
。
interface Obj {
prototype: any
case: (x: {[index: string]: (...args) => any}) => any
caseOn: (x: {[index: string]: (...args) => any}) => any
}
interface Union<T> {
(desc: T): T & Obj
}
var Type: Union<{[key: string]: any}>
export = Type
答案 0 :(得分:1)
我认为您所寻找的是索引类型,请参阅本手册的Advanced Types部分,了解有关其工作原理的更多说明。 我也一直在为paldepind / union-type制作一个声明文件,但它不完整:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Rec> data = new List<Rec>();
var rnd = new Random();
for (int i = 0; i < 3000; i++)
{
data.Add(new Rec() { Group = string.Format("Group{0}", rnd.Next(1,3)), Name = string.Format("Item{0}", rnd.Next(1,50)), Age = rnd.Next(10,100) });
}
var dataView = new ListCollectionView(data);
dataView.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
dataGrid.ItemsSource = dataView;
}
}
我也在尝试在TS中找到一个解决方法...
答案 1 :(得分:0)
如果你正在寻找一个可能的实现,这是我曾经写过的一个
Resu homework(double d[],int l){
Resu result;
..
.. your magic must be here
..
return result;
}
那就是说,我觉得它很无用,只需要知道/**
* A Maybe implementation
* that is JavaScript first
* i.e. simple typed abstraction over null/undefined
*/
export class Maybe<T>{
private _value: T;
/** Based on value it will be Some or None */
constructor(value: T) {
this._value = value;
}
/** Shorthand for constructor */
static Some<T>(value: T): Maybe<T> {
if (value === null || value === undefined) {
throw new Error('value for some cannot be null or undefied');
}
return new Maybe(value);
};
static None<T>(): Maybe<T> {
return new Maybe(null);
};
get value(): T {
return this._value;
}
get isSome() {
return this._value !== null && this._value !== undefined;
}
get isNone() {
return !this.isSome;
}
map<U>(mapper: (now: T) => U): Maybe<U> {
if (this.isSome) {
return new Maybe(mapper(this._value));
}
else {
return new Maybe(null);
}
}
}
并在对象上使用null/undefined
属性就更简单了(更多https://medium.com/@basarat/null-vs-undefined-in-typescript-land-dc0c7a5f240a)
所有说明的打字稿都将获得一流的可空性支持https://github.com/Microsoft/TypeScript/pull/7140,你将能够valid
并且你不会被允许分配{{1}一个数字,即number | null | undefined