You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript或相关库是否支持Scala式的_.成员调用简化写法?

TypeScript实现类似Scala的占位符属性访问语法

TypeScript本身不原生支持Scala那种_.y()或_.length的占位符语法,但可以通过以下几种方式实现带类型安全的类似效果:

1. 自定义类型安全的属性访问工具函数

自己实现一个简单的工具函数,就能达到简化代码的目的,同时完全保留类型推断:

const prop = <T, K extends keyof T>(key: K) => (obj: T): T[K] => obj[key];

// 使用示例
const strings = ['dog', 'cat', 'elephant'];
const stringLengths = strings.map(prop('length'));

TypeScript会自动推断prop('length')是(s: string) => number类型,完全符合Array.map的参数要求,类型安全有保障。

2. 使用函数式编程库

成熟的函数式库(如lodash/fp、Ramda)已经内置了这类工具,且自带完善的类型定义:

用lodash/fp的property方法

import { property } from 'lodash/fp';

const strings = ['dog', 'cat', 'elephant'];
const stringLengths = strings.map(property('length'));

用Ramda的prop方法

import { prop } from 'ramda';

const strings = ['dog', 'cat', 'elephant'];
const stringLengths = strings.map(prop('length'));

这些库的类型系统会自动适配上下文,不需要额外手动指定类型。

3. Proxy方案的局限性

你尝试的Proxy方案之所以难以保证类型安全,是因为Proxy的动态属性访问无法被TypeScript的静态类型系统准确捕获。如果非要模拟_语法,只能通过手动补全类型来勉强实现,但体验远不如前两种方案:

type Placeholder<T> = {
  [K in keyof T]: (obj: T) => T[K];
};

const _ = new Proxy({}, {
  get(_, prop) {
    return (obj: any) => obj[prop];
  }
}) as Placeholder<any>;

// 使用时必须显式指定类型,否则类型推断失效
const stringLengths = strings.map(_.length as (s: string) => number);

这种方式需要手动维护类型关联,一旦类型变更容易出错,不推荐作为常规方案。


内容的提问来源于stack exchange,提问作者A Question Asker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:47:27