logo
Tags down

shadow

Typescript assign value for keyof not working


By : Full Stack
Date : September 16 2020, 03:00 PM
To fix the issue you can do Object.keys(obj) returns string[], that's why m is a string, but dataTypes is "a" | "b" | "c" (union type), i.e more restrictive. So you can't assign a string to a variable of type "a" | "b" | "c".
The solution is simple: don't use Object.keys(obj):
code :
function check<T extends Base>(obj: T, key: string) {
  type dataTypes = keyof T;
  for (let m in obj) {
    const temp: dataTypes = m;
  }
}


Share : facebook icon twitter icon

Typescript confusion in generic `keyof` `extends keyof` `typeof` and others


By : Techseria
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further For the first issue, the problem with your approach for the V parameter is that you specify the default for it, but that does not mean V MUST extend T[P], just that that is the default, you can invoke the constructor with really any type parameter for V. Just use T[P] where appropriate, as even if you constrain it properly (V extends T[P] = T[P]) the compiler it will still not be able to correctly follow that V is assignable from T[P].
code :
export class ModelProperty<T, P extends keyof T> {
    constructor(public name: P, public value: T[P]) { }
    fun(t: T){
        let value = t[this.name]; // is T[P]
    }
}
export class ModelProperty<T, P extends keyof T> {
    constructor(public name: P, public value: T[P]) { }

    static for<T>() {
        return function <P extends keyof T>(name: P, value: T[P]){
            new ModelProperty<T, P>(name, value);
        } 
    }
}
const carModelCreator = ModelProperty.for<Car>();
let engine2 = carModelCreator('engine','22'); // Gives error as '22' should be number.. working great.
let engine1 = carModelCreator('engine',2); // But there is repeatation 'engine', 'engine'
export class ModelProperty2<T, P extends keyof T,  P2 extends keyof T[P]> {
    constructor(public name: [P, P2], public value: T[P][P2]) { }

    static for<T>() {
        return function <P extends keyof T, P2 extends keyof T[P]>(name: [P, P2],  value: T[P][P2]){
            new ModelProperty2<T, P, P2>(name, value);
        } 
    }
}
const carModelCreator = ModelProperty2.for<Car>();
let engine2 = carModelCreator(['detials', 'good'],'22'); //error 
let engine2 = carModelCreator(['detials', 'good'],'Boy'); //ok
export class ModelProperty<T, V> {
    constructor(public name: string[], public value: V) { }


    static for<T>() {
        function helper<P extends keyof T, P2 extends keyof T[P]>(name: [P, P2],  value: T[P][P2])
        function helper<P extends keyof T>(name: [P],  value: T[P])
        function helper(name: string[],  value: any){
            return new ModelProperty<T, any>(name, value);
        } 

        return helper;
    }
}
const carModelCreator = ModelProperty.for<Car>();
let engine1 = carModelCreator(['engine'], 22); // ok
let engine2 = carModelCreator(['detials', 'good'],'Boy'); //ok

Typescript function with keyof doesn't accept object key value as valid keyof


By : user2469433
Date : March 29 2020, 07:55 AM
wish of those help The problem is that typescript does not infer by default literal types for object properties (even if they are const).
You can get around this by using a type assertion to the string literal type:
code :
const c = {
  age: 'age' as 'age'
}

test(c.age);
const c = (<V extends string,  T extends Record<string, V>>(o: T) => o)({
  age: 'age'
});

test(c.age);
const c = {
  age: 'age'
} as const

test(c.age);

Typescript: for (let key in obj), `key` is `Extract<keyof T, string>` instead of just `keyof T`, why?


By : user2533177
Date : March 29 2020, 07:55 AM
hop of those help? TypeScript 2.9 expanded key types to include number and symbol types also.

TypeScript, VSCode: keyof type not working as expected when switching to insider version of vscode


By : Mati Selg
Date : March 29 2020, 07:55 AM
To fix the issue you can do Since you are using the insider version of vs code, you are probably using typescript 3.5. This release has a breaking change.
The basic idea is that until now typescript allowed write operations to obj[k] = v where k: keyof typeof obj if v was a union of possible values in obj:
code :
let o = { nr: 0, str: "" }
declare let k: keyof typeof o;
o[k] = 0
o[k] = ""
function updateTransaction(k: TransactionKey, v: ITransaction[TransactionKey]) {
    if (testState.selectedTransaction) {
        testState.selectedTransaction[k] = v as any;
    }
}

How to avoid dynamic keyof object assign error in TypeScript


By : Annabella Nova
Date : September 28 2020, 04:00 AM
Hope that helps There is no good way to avoid a type assertion here. In recent version on TS (post 3.5 I think) when writing through an index the value written has to be compatible with all possible property values specified by the key. In your case that would be number & string which reduces to never hence the error.
The root cause is that TS does not keep track of variables only of types, so as far as the types are concerned, your example would be no different from:
code :
let key1 = 'id' as  keyof User;
let key2 = 'name' as  keyof User;
//Obvious error
user1[key1] = user2[key2] // same error, TS can't distingusih between this and your user1[key] = user2[key]

type User = {
  id: number,
  name: string,
}


let user1: User = { id: 123, name: "Hello" };
let user2: User = { id: 456, name: "World" };
for (let key of keys) {
  user1[key] = user2[key] as never
}

type User = {
  id: number,
  name: string,
}


let user1: User = { id: 123, name: "Hello" };
let user2: User = { id: 456, name: "World" };

let keys: (keyof User)[] = ["id", "name"];

for (let key of keys) {
  set(user1, key, user2[key])
}
Related Posts Related Posts :
  • Submit button with different functions
  • Chrome extension does not recognise getElementsByClassName("listBodyRow")[i] but running in chrome console wor
  • How to validate and display form data using ES6 Javascript class
  • Initialize object with type [key, value: Array] in shorthand form
  • How can I reduce cyclomatic complexity for the code to be acceptable by sonar
  • React Hooks: Handling Objects as dependency in useEffects
  • Creating a Second Blog Template on Gatsby
  • Use async / await in parallel, and get results as they arrive?
  • Why does the PHP file not read the javascript properly?
  • Filter JavaScript array based on object property from another array
  • How to get the first class that a class extends without creating an instance
  • Appending window.location in src
  • How to modify objects in an array?
  • React insert node object
  • WebSockets with functional components
  • Parse JSON string using node.js
  • How to make a select disabled in Laravel5?
  • How can I get the total number for an object's properties in typescript?
  • Three.js - antialiasing, rendering, fxaa
  • regex for valid web url and html telephone url
  • Second call to Mathjax typeset function from jQuery not working
  • I can't delete empty value of my String array
  • Sencha allowBlank config property is not applying for TextField widget
  • Ways to prevent survey respondents from inputting spaces as their first character
  • Forcing ~synchronous Node.js IPC
  • Why React.js doesn't bind it's function with this object by default
  • Javascript Affecting Image Position
  • Javascript eval ReferenceError is not defined
  • add <meta> tag to editor in prestashop 1.6
  • Javascript loop through object keys
  • How to write a function that recognises unbalanced brackets
  • Condition CSS based on OS
  • group array of objects by id
  • $(window) equivalent and other Jquery to Vannilla JS is not working
  • Send web push notification to all subscribers in one call
  • async script src inside script tag, GDPR complilance google ads
  • Modify Javascript object that API sends
  • Ajax call not triggering
  • How to get everything between two words
  • React Props for Handle Change not a Function
  • How i can iterate over nested section elements?
  • React Native ViewPager with a KeyboardAvoidingView as parent doesn't keep the keyboard up - iOS
  • List field contents not displaying with .val function
  • GET error 400 bad request on second axios api call
  • React & dealing with asynchronous state
  • How to see if an array has a value, and return true if it does. - JavaScript
  • Extract a phone number from a web page then do something with it
  • Unit testing ember-concurrency tasks and yields
  • Not able to read below JSON using Angular 7
  • Load Content for Bootstrap 4 Modal Externally Using JavaScript/ jQuery
  • How to add a material (.mtl) to an object (.obj) using three.js?
  • prevent remount when component is wrapped in parent
  • How to find the values form array of objects
  • How to send multiple data using ajax jquery?
  • Add two columns and display result in third column in HTML Table
  • Adding a class to an object depending on which file the object is being used
  • Manipulating SVG Path Coordinate with Vanilla JavaScript
  • how to fix heroku error while deploying an expressjs app?
  • Fetching past messages into a file
  • Check if click linked in array has a submenu key value. IF true run some code ELSE run other code
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk