打字稿:如何仅从类型中提取可选键?

时间:2018-12-22 22:20:09

标签: typescript

假设我有这样的类型:

type User = {
  uid: string,
  displayName?: string,
  bestFriend?: string,
}

是否可以使用 某种映射类型?我正在寻找如何定义 OptioanlProperties<T>在下面输入。

type OptionalUserProperties = OptionalProperties<User>
// type OptionalUserProperties = "displayName" | "bestFriend"

我的用例是计算一个UpdateOf<User>类型,该类型允许特定 “操作”值,例如DeleteProperty,将被分配给基本类型中可选的键。

export type UpdateOf<T> =
  // optional fields may be their own type, or the special DeleteProperty type.
  { [P in OptionalProperties<T>]?: T[P] | DeleteProperty } &
  // required fields may be changed, but cannot be deleted.
  { [P in Diff<keyof T, OptionalProperties<T>>]?: T[P] }

1 个答案:

答案 0 :(得分:3)

是:

    public Directory getDir(String name) {
            Iterator<Component> iterator = (Iterator<Component>) components.iterator();
            Component component = null; 
            while(iterator.hasNext()) {
                component = iterator.next();
            if(component instanceof Directory) {
                if(component.getName().equals(name)) {
                    return (Directory) component;
                    }
                else component.getDir(name);
            }
        }

        return null;
    }