打字稿:对象类型到数组类型(元组) [英] Typescript: object type to array type (tuple)

查看:30
本文介绍了打字稿:对象类型到数组类型(元组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

interface Obj {
    foo: string,
    bar: number,
    baz: boolean
}

所需的类型是这个元组:

The desired type is this tuple:

[string, number, boolean]

如何将接口转换为元组?

How can I convert the interface to the tuple?

更新:

我原来的问题是:我制作了一些具有声明精神的固执己见的库,用户应该在其中描述对象文字中函数的参数.像这样:

My original problem is: I make some opinionated library with a declarative spirit, where a user should describe parameters of a function in an object literal. Like this:

let paramsDeclaration = {
  param1: {
    value: REQUIRED<string>(),
    shape: (v) => typeof v === 'string' && v.length < 10
  },
  param2: {
    value: OPTIONAL<number>(),
    ...
  },
}

然后库接受这个对象并创建一个带有参数的函数:

Then the library takes this object and creates a function with parameters from it:

   (param1: string, param2?: number) => ...

所以,制作这样的功能不是问题,问题是正确输入,让用户获得良好的代码补全(IntelliSense).

So, making such function is not a problem, the problem is to correctly type it, so that user gets good code-completion (IntelliSense).

附言我知道它无法解决,但知道什么是最接近的解决方法/hack 会很有趣.

P.S. I know it's not solvable, but it would be interesting to know what is the closest possible workaround/hack.

推荐答案

并不是问题的真正答案,但由于我实际上认为这不可能做到,希望这至少在某种程度上有所帮助:

Not really an answer to the question, but since I don't actually think its possible to do, hopefully this is at least helpful in some way:

function REQUIRED<T>(): T {
    //...
}
function OPTIONAL<T>(): T {
    //...
}

interface ParamsDeclaration {
    readonly [paramName: string]: {
        readonly value: any;
        readonly shape?: Function;
    };
}

type Func<T> = T extends {
    readonly [paramName: string]: {
        readonly value: infer U;
    };
} ? (...params: Array<U>) => void
    : never;

function create<T extends ParamsDeclaration>(paramsDeclaration: T): Func<T> {

    // ...
}

const paramsDeclaration = {
    param1: {
        value: REQUIRED<string>(),
        shape: (v: any) => typeof v === 'string' && v.length < 10
    },
    param2: {
        value: OPTIONAL<number>(),
        //...
    },
};
// Type is '(...params: (string | number)[]) => void'
const func1 = create(paramsDeclaration);
func1('1', 2); // Ok
func1(2, '1'); // Ok, but I assume not what you want
func1(Symbol()); // TS error

这篇关于打字稿:对象类型到数组类型(元组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆