打字稿类型缩小

时间:2018-02-27 10:47:57

标签: typescript

我有一些代码呈现了一个标签控件,它正在查看传入的反应孩子,但我不知道它是单个项目还是数组。如果没有使用任何一种方法,是否有更清洁的方法?我试图让类型缩小工作但是没有成功。

class BLEU(object):
    # add self in the functions
    def compute(self, candidate, references, weights):
        ...
        # don't do this
        # bp = BLEU.brevity_penalty(candidate, references)
        # instead call the method from like this:
        bp = self.brevity_penalty(candidate, references)
        ...

    def modified_precision(self, candidate, references, n):
        ...

    def brevity_penalty(self, candidate, references):
        ...

2 个答案:

答案 0 :(得分:3)

检查其数组是否为Array.isArray(input)input instanceof Array

https://www.w3schools.com/jsref/jsref_isarray.asp

if (Array.isArray(input)) return input;
if (input === undefined) return [];
return [input];

答案 1 :(得分:1)

我会做像

这样的事情
EnsureArray<T extends React.Component>(inputs: ReadonlyArray<T>): ReadonlyArray<T>;
EnsureArray<T extends React.Component>(input: T): T[];
EnsureArray<T extends React.Component>(input: T | ReadonlyArray<T> | undefined): any[] {
    if (input === undefined) { return []; }

    return Array.isArray(input)
        ? input
        : [input];
}
相关问题