繁体   English   中英

是否可以从 TypeScript 接口创建“空” object 接口?

[英]Is it possible to create an “empty” object from a TypeScript interface?

假设您有一个非常大的 object 定义为 TypeScript 接口:

interface AccountInterface {
  accountIdentifier?: string;
  sid?: string;
  idToken?: {
    aio?: string;
  };
  idTokenClaims?: {
      aio?: string;
  };
}

我希望 object 始终具有其属性和子属性。 它们可以是字符串或空字符串:

let account = {
  accountIdentifier: "",
  sid: "",
  idToken: {
    aio: "",
  },
  idTokenClaims: {
    aio: "",
  },
};

阅读其他问题,我认为可以做到这一点:

const emptyAccount = {} as AccountInterface

console.log('emptyAccount ', emptyAccount)
console.log('emptyAccount.sid ', emptyAccount.sid)

但这不会创建一个 object ,其所有属性都是所需的空字符串。

如果这样的事情是可能的,那就太好了,所以没有必要在代码中复制 object,因为一个用于接口,一个用于 object 具有空字符串属性。

您可以创建一个实现该interfaceclass ,添加默认值,并使用它来创建您的对象。 您仍在其他地方重写相同的结构,但现在您只需执行一次,如果您愿意,可以使用constructor函数用不同的值初始化 object。

interface AccountInterface {
  accountIdentifier?: string;
  sid?: string;
  idToken?: {
      aio?: string;
  };
  idTokenClaims?: {
      aio?: string;
  };
}

class Account implements AccountInterface {
  accountIdentifier = '';
  sid = '';
  idToken = { aio: '' };
  idTokenClaims = { aio: '' };
}

const emptyAccount = new Account();

此外,正如@apokryfos 所指出的,您还可以使用 class 来键入对象,因此无需同时定义instanceclass除非您要使用尚未使用 ZA2F21ED4F8EBC2ABCBDZ4 创建的对象实现该实例(因为那些没有在类中定义的方法)。

如果你想避免使用class并使用function做类似的事情,你完全可以:

function createAccount(): AccountInterface {
  return {
    accountIdentifier = '';
    sid = '';
    idToken = { aio: '' };
    idTokenClaims = { aio: '' };
  };
}

const emptyAccount = createAccount();

const emptyAccount = {} as AccountInterface应该创建一个 object。 但是您的 AccountInterface 仅包含可能存在但不能存在的属性(因为?)。 所以一个空的 object 完全匹配您的 AccountInterface。

如果您想包含一个具有默认值的属性,那么您必须在您的界面中声明它。

interface AccountInterface {
    accountIdentifier: string|null // <- will be included in {} as AccountInterface
    sid?: string // <- will not be included in {} as AccountInterface
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM