guid/uuid in Typescript Node.js app

自闭症网瘾萝莉.ら 提交于 2019-12-12 07:39:09

问题


I try to make a uuid (v 3.0.1) package work in Node/Typescript app, but I'm not sure what should I import and how to use it.

This is index.d.ts (from @types/uuid v 2.0.29):

declare namespace uuid {
    interface V1Options {
        node?: number[];
        clockseq?: number;
        msecs?: number | Date;
        nsecs?: number;
    }

    type V4Options = { random: number[] } | { rng: () => number[]; }

    interface UuidStatic {
        (options?: V4Options): string;
        (options: V4Options | null, buffer: number[], offset?: number): number[];
        (options: V4Options | null, buffer: Buffer, offset?: number): Buffer;

        v1(options?: V1Options): string;
        v1(options: V1Options | null, buffer: number[], offset?: number): number[];
        v1(options: V1Options | null, buffer: Buffer, offset?: number): Buffer;
        v4: UuidStatic;
        parse(id: string): number[];
        parse(id: string, buffer: number[], offset?: number): number[];
        parse(id: string, buffer: Buffer, offset?: number): Buffer;
        unparse(buffer: number[] | Buffer, offset?: number): string;
    }
}

declare const uuid: uuid.UuidStatic
export = uuid

I cant find exported class here.

For example index.d.ts from angular2-uuid looks like that:

export declare class UUID {
    constructor();
    static UUID(): string;
    private static pad4(num);
    private static random4();
}

And it's quite obvious to use:

let id = UUID.UUID();

So. How to use (import and call) uuid?


回答1:


Yes, here is code from my project:

import { v4 as uuid } from 'uuid';
const id: string = uuid();



回答2:


Per the tests:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/354cec620daccfa0ad167ba046651fb5fef69e8a/types/uuid/uuid-tests.ts

import uuid = require('uuid');

let uuidv4: string = uuid.v4();



回答3:


This also works for me:

import uuidv4 from 'uuid/v4'

this.projectId = uuidv4()



回答4:


import * as uuid from "uuid";
const id: string = uuid.v4();


来源:https://stackoverflow.com/questions/43837659/guid-uuid-in-typescript-node-js-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!