打字稿:如何确保泛型类型是JSON的子集?

时间:2016-12-15 19:17:23

标签: json typescript

我想这样做:

interface IJSON {
  [key: string]: string | number | boolean | IJSON |
                 string[] | number[] | boolean[] | IJSON[];
}

function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T {
  return json;
}

let good = {
  message: 'i work',
};

let bad = {
  date: new Date(),
};

// good is a subset of IJSON so everything works!
iAcceptOnlyJSON(good);

// bad is not a subset of IJSON so this should give me an error
iAcceptOnlyJSON(bad);

当然,在Typescript中没有“subsetof”。有没有办法在打字稿中获得此功能?

1 个答案:

答案 0 :(得分:0)

您非常接近 - 语言功能称为generic parameter constraints,而使用的关键字代替subsetofextends

function iAcceptOnlyJSON<T extends IJSON>(json: T): T {
  return json;
}

iAcceptOnlyJSON(bad)的错误消息是

"Argument of type '{ date: Date; }' is not assignable to parameter of type 'IJSON'.
      Property 'date' is incompatible with index signature.
        Type 'Date' is not assignable to type 'string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]'.
          Type 'Date' is not assignable to type 'IJSON[]'.
              Property 'length' is missing in type 'Date'."

但这并非万无一失 - 所有structurally compatible stringamount_of_names = int(input("Input amount of players: ")) names = [] for counter in range(amount_of_names): name = str(input("Input players first name: ")) names.append(name) #print (names) selected_name = str(input("Input your name: ")) import random names = random.choice(names) while True: name in names import random names = random.choice(names) break print (names) 但不是字符串的内容也会传递。