匹配“任何”但不匹配数组

时间:2019-02-06 20:26:55

标签: typescript

我正在尝试键入一个返回any而不是array的函数。

类似这样的东西:

Not<any, any[]>

interface Specific {
  name: string;
}

const makeOneCore = (): any => {
  return {};
};

const makeManyCore = (): any[] => {
  return [{}];
};

const makeOne = (): Specific => {
  return makeOneCore();
};

const makeMany = (): Specific[] => {
  return makeManyCore();
};

const makeManyShouldFail = (): Specific[] => {
  return makeOneCore();
};

我想输入makeOneCore,以使makeManyShouldFail是打字错误,因为它应该与any相匹配,并可能是array

寻找某种方式hello有效而boom无效。

type NotArray<T> = T extends Array<any> ? never: T;

type v = NotArray<Array<any>>;

const hello: v = {};
const boom: v = [];

console.log({ hello, boom });

1 个答案:

答案 0 :(得分:3)

尝试这样的事情

pragma solidity 0.4.25;

import "./interfaces/IMyContract.sol";

/**
 * @title My Contract.
 */
contract MyContract is IMyContract {
    string public constant version = "1.0.0";

    mapping(bytes32 => address) private something;

    event Event(bytes32 indexed _var1, address indexed _var2);

    /**
     * @dev ...
     * @param _var3 ...
     * @param _var4 ...
     */
    constructor(bytes32[] memory _var3, address[] _var4) public {
        uint256 length = _var3.length;
        require(length == _var4.length);
        for (uint256 i = 0; i < length; i++) {
            require(uint256(something[_var3[i]]) == 0);
            something[_var3[i]] = _var4[i];
            emit Event(_var3[i], _var4[i]);
        }
    }

    /**
     * @dev ...
     * @param _var5 ...
     */
    function get(bytes32 _var5) external view returns (address) {
        return something[_var5];
    }
}

类型type NotArray<T> = T extends Array<any> ? never: T; type A = NotArray<Array<any>>; // never type B = NotArray<Array<string>>; // never type C = NotArray<boolean>; // boolean 可以分配给任何其他类型