1

I want to construct type {name:string,value:string} from another type Todo.

Below code throws error: Property '0' does not exist on type 'Pick<Todo, "items">'.

type Todo = {
  title: string;
  items:Array<{name:string,value:string}>;
  description: string;
  completed: boolean;
}
 
type TodoItems = Pick<Todo, "items">[0]; //ERROR: Property '0' does not exist on type 'Pick<Todo, "items">'.
 
const todo: TodoItems = {
  name: "Clean room",
  value: "yes",
};

Note: Todo comes from a ts module so it's not editable.

What approach could I follow to extract {name:string,value:string} from Todo?

3 Answers 3

4

I think you need to split Todo item into separate type as Dmitrii Zolotuhin said, it will be the rightest way. BUT if you can't do it, you can create this type

type TodoItems = Todo["items"][number]
// ...or
type TodoItems = Pick<Todo, "items">["items"][number]

Typescript playground

Sign up to request clarification or add additional context in comments.

Comments

2

You were almost right, try type TodoItems = Todo["items"][0];

type Todo = {
  title: string;
  items:Array<{name:string,value:string}>;
  description: string;
  completed: boolean;
}
 
type TodoItems = Todo["items"][0]; 
//... 

Playground Link

Comments

1

I would do it in the other way:

interface TodoItem {
    name: string
    value: string
}

interface Todo {
    title: string
    items: TodoItem[]
    description: string
    completed: boolean
}

const todo: TodoItem = {
    name: "Clean room",
    value: "yes",
}

1 Comment

thanks for alternative solution but due to some constraints I want to extract type of array from an existing type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.