Skip to content

Is this possible? Opposite of Partial Type #12578

Closed
@opensrcken

Description

@opensrcken

TypeScript Version: nightly

Code

interface Test {
  optional?: string;
}

function getProperty<K extends keyof Test>(t: Test, key: K): Test[K]|never {
  if (t[key]) {
    return t[key];
  }
  throw new Error('Value does not exist at key');
}

const a: string = getProperty({}, 'optional');

Target behavior:
The given function is coded such that it will always return a non-empty value, so it would be great if there were a way to make something like this compile. Is there a way to communicate the opposite of Partial<T>, e.g. that we know Test[K] will be non-empty?

Actual behavior:
error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions