简体   繁体   English

将 javascript 链式设置器转换为 typescript

[英]Converting javascript chained setter to typescript

I've been using this idiom in javascript to create chained setters.我一直在 javascript 中使用这个成语来创建链式设置器。

function bar() {

    let p = 0;

    function f() {
    }

    f.prop = function(d) {
        return !arguments.length ? p : (p = d, f);
    }

    return f;

}

This allows me to do an easy creation and setting as const b = bar().prop(2) , having b as the function and allowing more chained statements to be appended.这使我可以轻松创建和设置为const b = bar().prop(2) ,将b作为 function 并允许附加更多的链接语句。 And it works for getting the property by using b.prop() , which of course can't be chained further.它适用于使用b.prop()获取属性,当然不能进一步链接。

I'm trying to convert this to TypeScript and found this solution, that although it correctly allows the typing, it seems obscure.我正在尝试将其转换为 TypeScript 并找到此解决方案,尽管它正确地允许打字,但它似乎晦涩难懂。

p.prop = (...args: [number?]) => !args.length ? p : (p = args[0]!, f);

This becomes even more obscure when there are multiple types for the argument.当参数有多种类型时,这变得更加模糊。

p.prop = (...args: [(number | boolean)?]) => !args.length ? p : (p = args[0]!, f);

Is there any idiomatic typescript way to do this setting and getting?是否有任何惯用的 typescript 方式来进行此设置和获取?

Because the prop function accepts only one possible argument, you can make the Typescript version more similar to the Javascript (and more simple) by simply declaring d as optional, then checking whether it exists.因为prop function 只接受一个可能的参数,您可以通过简单地将d声明为可选,使 Typescript 版本更类似于 Javascript (然后更简单)。 There's no need for rest syntax or an array:不需要 rest 语法或数组:

f.prop = function(d?: number) {
    return d === undefined ? p : (p = d, f);
}

For additional types, simply add the type to the d parameter, and since it's going to be assigned to p , also declare the type of p :对于其他类型,只需将类型添加到d参数中,并且由于它将分配给p ,因此还要声明p的类型:

function bar() {
    let p: number | boolean = 0;
    function f() {
    }
    f.prop = function (d?: number | boolean) {
        return d === undefined ? p : (p = d, f);
    }
    return f;
}
const b = bar().prop(2)

You can declare a function interface like:您可以声明一个function 接口,如:

interface Chainable {
    (): void;
    prop: (d: any) => Chainable
};

function bar(): Chainable {
   ... 
   const fChainable = f;
   return fChainable;

} }

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

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