Typescript数组到字符串并集

时间:2019-12-11 13:40:51

标签: typescript

我需要将数组转换为字符串并集。见下文

export class Foo<K extends string[]> {
    make<L extends string[]>(keys: L): Foo<L> {
        return new Foo();
    }
    get(key: K) {

    }
}

const x = Foo.make(['a', 'b'])

// need to constraint this to 'a' | 'b'
x.get('')

1 个答案:

答案 0 :(得分:1)

第一个问题是调用make时捕获字符串文字。您可以通过以下几种方式之一进行操作。您可以在其他参数中使用元组(make<L extends string[]>(...keys: L): Foo<L>,但这需要您将make函数调用为Foo.make('a', 'b')

另一种选择是利用以下事实:如果将文字类型分配给约束为string的类型参数,编译器将保留这些文字类型。这将保留当前的调用方式。

获取联合的问题很简单,您可以使用type query

export class Foo<K extends string[]> {
    static make<L extends V[], V extends string>(keys: L): Foo<L> {
        return new Foo();
    }
    get(key: K[number]) { // index type

    }
}

const x = Foo.make(['a', 'b'])

x.get("a")
x.get("A") // err

Playground Link

另一种选择是不使用L中的元组类型,只需在调用make时直接捕获并集即可:

export class Foo<K extends string> {
    static make<V extends string>(keys: V[]): Foo<V> {
        return new Foo();
    }
    get(key: K) { // index type

    }
}

const x = Foo.make(['a', 'b'])

x.get("a")
x.get("A") // err

Playground Link