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

TypeScript中如何根据参数类型进行条件分支赋值

问题描述

以下是我的代码:

class ImmutableArraySlice<Type> implements Iterable<Type>
{
    private _source: Array<Type>;
    private _start: number;
    private _end: number;

    constructor(from: Array<Type> | ImmutableArraySlice<Type>, start: number = 0, end?: number)
    {
        this._source = ( /* 检查'from'是否为ImmutableArraySlice类型 */ ) ? from._source : from;
        this._start = start;
        this._end = end ?? source.length;
    }
    ...
}

我需要根据输入参数的类型为this._source分配不同的值,但不知道该如何实现。我知道JS/TS不支持多构造函数,因此陷入困境。

编辑1:已修改代码进一步明确我的目标(确实不像我想的那么明显,抱歉)


解决方案

在TypeScript中,你可以通过类型守卫来判断from的类型,从而完成this._source的正确赋值,以下是两种可行方案:

1. 使用instanceof直接判断

因为ImmutableArraySlice是类类型,instanceof可以直接识别实例所属类:

constructor(from: Array<Type> | ImmutableArraySlice<Type>, start: number = 0, end?: number)
{
    this._source = from instanceof ImmutableArraySlice ? from._source : from;
    this._start = start;
    // 修复原代码的未定义错误:将source改为this._source
    this._end = end ?? this._source.length;
}

2. 自定义类型守卫(适用于更复杂的类型判断场景)

如果后续需要扩展类型判断逻辑,可以编写自定义类型守卫函数:

// 自定义类型守卫,判断值是否为ImmutableArraySlice实例
function isImmutableArraySlice<T>(value: Array<T> | ImmutableArraySlice<T>): value is ImmutableArraySlice<T> {
    return '_source' in value && Array.isArray((value as ImmutableArraySlice<T>)._source);
}

// 在构造函数中使用
constructor(from: Array<Type> | ImmutableArraySlice<Type>, start: number = 0, end?: number)
{
    this._source = isImmutableArraySlice(from) ? from._source : from;
    this._start = start;
    this._end = end ?? this._source.length;
}

另外注意原代码中end ?? source.length存在变量未定义问题,必须改为this._source.length才能正确获取源数组长度。


内容的提问来源于stack exchange,提问作者LoC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:19:56