网站搜索

TypeScript中的Scala下划线——已实现但无法输入


很确定这是不可能的,这已经是我两年来的一个个人项目,试图在 Typescript 中实现 Scala 的下划线语法,但始终无法实现。这是实现方式和效果。

我唯一关心类型的是“下划线”,其他的都忽略。

const buildUnderscore = (f: any) => (path: any[]): any => new Proxy(f, handler(path));
const handler = (path: any[]) => ({
    get: function(obj: any, prop: any, value: any) {
        return buildUnderscore((a: any) => getAtPath(a, path.concat(prop)))(path.concat(prop));
    }
})
/* takes object A and key path ["a", "b", "c"] -> returns A["a"]["b"]["c"] */
const getAtPath = (obj: any, [head, ...tail]: string[]): any => {
    if(head === undefined) return obj;
    return getAtPath(obj[head], tail);
}


/* Ignore all implementation above i don't care if its typed this is the only thing i care that's typed */
const _: Underscore = buildUnderscore((a: any) => a)([]);


// ConvertKeysToFunctions<GetArgs<Array<T>["map"]>[0]> is what i need
// but there's no way to infer T
// where GetArgs gets the first argument of Array["map"]
// and ConvertKeysToFunctions converts that types keys to function types
type Underscore = <T>(a: T) => T

const data =  [
        {
            child: {
                name: "bob",
                children: ["sue", "john"]
            }
        },
        {
            child: {
                name: "catness",
                children: ["rue", "hew"]
            }
        },
    ]
console.log(data.map(_))  // converts to data.map((a) => a)
console.log(data.map(_.child.children[0]))// converts to: data.map((a) => a["child"]["children"][0])
console.log(data.map(_.child))  // converts to data.map((a) => a["child"])

答案#1

不幸的是,TypeScript 目前缺乏引用对象属性动态名称的能力,这使得代理在 TypeScript 中很难使用或类型化。

你能做到的最接近的方法大概就是使用一个 lambda:

_ => _.foo.bar

如果路径上的任何属性是可选的,你将不得不使用像我在库中为类似目的所做的那种黑暗类型魔法。不过请注意,使用这样的东西可能会显著减慢编译过程。