如何将数字类型的值转换为空字符串?

时间:2019-01-16 20:19:18

标签: typescript type-conversion

我正在使用这种TypeScript数据结构(由于类型的原因,TypeScript很重要):

  private data = {
    parent_id: 0,
    name: ''
  };

我想要这个:

  private data = {
    parent_id: '',
    name: ''
  };

如何将parent_id:number字段转换为parent_id:string

3 个答案:

答案 0 :(得分:1)

您可以定义如下接口:

interface DataInterface {
  parent_id: number | string;
  name: string;
}

然后您可以定义对象:

const data: DataInterface = {
  parent_id: 0,
  name: 'foo'
};

这也是允许的:

data.parent_id = '';

答案 1 :(得分:1)

我们实际上可以告诉编译器使用条件类型和typeof关键字为我们进行区分。见下文:

type isZero<N> = N extends (0 | '') ? '' : number;
type ParentIdType = isZero<typeof instance.id>;

interface Data {
    parent_id: ParentIdType;
    name: string;
}

class SomeClassWithData {
    readonly id = <your value>;

    private data: Data = {
        parent_id: this.id,
        name: 'foo',
    }
}

const instance = new SomeClassWithData();

工作原理

之所以可行,是因为编译器将常量和只读类属性作为其文字类型进行推断。这是instance.id = 0;时的工作方式示例:

type isZero<N> = N extends (0 | '') ? '' : number; // '' because 0 extends 0
type ParentIdType = isZero<typeof instance.id>;  // isZero<0>

interface Data {
    parent_id: ParentIdType;  // ParentIdType --> isZero<0> --> ''
    name: string;
}

class SomeClassWithData {
    readonly id = 0; // inferred as type 0 instead of number because it's a readonly property

    private data: Data = {
        parent_id: this.id,  // Error: Type 'number' is not assignable to type '""'.
        name: 'foo',
    }
}

const instance = new SomeClassWithData();

此解决方案很好,因为

instance.id = 1;

instance.id = '';

被允许,但是

instance.id = 0;

instance.id = 'foo';

将引发错误。

答案 2 :(得分:0)

我认为最好的办法是先将其ID定义为字符串,然后再将其输入到数据类中,即

 id = '0';
 private data = {
     parent_id: id,
     name: ''
 };

在整个过程中,如果您有其他ID作为字符串,则可以将其设置为变量,并使用.toString()函数,该函数会自动将数字转换为字符串,然后可以复制我在上面所做的事情。