简体   繁体   English

typescript 中是否有任何方法可以定义带有类型的可选字段?

[英]Is there any way in typescript to define optional field with type?

I need something like that:我需要这样的东西:

interface A {
 a: SomeUtilityType<number>;
}

to be equivalent to:相当于:

interface A {
 a?: number;
}

I know that I can use Optional from 'utility-types':我知道我可以使用“实用程序类型”中的Optional

import { Optional } from 'utility-types';

type B = Optional<A, 'a'>

but I need exactly usage like this:但我需要这样的用法:

interface A {
 a: SomeUtilityType<number>;
}

If you are looking how to define optional field in interface, you can use question mark the same as in you first example如果您正在寻找如何在界面中定义可选字段,您可以使用与第一个示例相同的问号

interface A {
 a?: SomeUtilityType<number>;
}

?: operator can be used with primitives, and any other types too ?:运算符可以与原语一起使用,也可以与任何其他类型一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Typescript中定义带有可选参数的function类型? - How to define function type with optional parameter in Typescript? 如何定义类型的任何属性子项? typescript - How to define type any of property children? typescript 如何在打字稿中定义“任何字符串枚举”类型? - How to define the type "any string enum" in typescript? Typescript:定义一个类型 T 使得 T &amp; {'a': any} == R - Typescript: Define a type T such that T & {'a': any} == R 打字稿:定义类型的对象,但根据需要推断提供了可选的道具 - Typescript: define object of type, but infer provided optional props as required 如何使用 TypeScript 中联合类型的可选道具定义 object - how to define an object with optional props from an union type in TypeScript 如何使用 TypeScript 中的非可选键子集定义映射类型? - How to define Mapped type with a non-optional subset of keys in TypeScript? 如何在取决于可选参数的 TypeScript 输出类型中定义 - How to define in TypeScript output type which depends on optional parameter 在 typescript 中,有没有办法通过 typeof 数据定义全局窗口的扩展类型? - In typescript, is there any way to define global window's extended type via typeof data? 有没有办法在打字稿中定义新的(而不是别名)类型? - is there a way to define a new (instead of aliasing) type in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM